diff --git a/README.md b/README.md index 6ed57ba..e4fb121 100644 --- a/README.md +++ b/README.md @@ -177,6 +177,61 @@ notices: задайте `notices: []` или удалите файл. Все объявления — обычные ссылки, которые открываются без JavaScript. +## Пользовательские спрайты + +Слоистые спрайты сообщества задаются в `community-sprites.json` в корне +**es-doc-assets**. Формат: `groups` → название группы → `variations` → +вариант с `name` и `distances`. Каждая дистанция (`normal`, `close`, `far`) +содержит непустой массив путей к слоям, от нижнего к верхнему. + +```json +{ + "groups": { + "Лена в полицейской форме": { + "author": {"name": "Имя художника", "link": "https://example.com/artist"}, + "description": "Спрайт из модификации «Главный Атрибут Пионера»", + "variations": [ + { + "name": "Улыбается", + "distances": { + "normal": [ + "/resource/raw/images/sprites/normal/un/un_1_body.png", + "sprites/lena_police/normal/clothes.png", + "sprites/lena_police/normal/smile.png" + ], + "close": ["sprites/lena_police/close/smile.png"], + "far": ["sprites/lena_police/far/smile.png"] + } + } + ] + } + } +} +``` + +Это пример структуры: пользовательские файлы нужно добавить в репозиторий. +Относительные пути отсчитываются от `community/`; +`/resource/community/…` адресует ту же папку, `/resource/raw/…` — `game/`. +Используйте `/` в путях. Внешние ссылки и выход за пределы этих папок запрещены. +Поддерживаются PNG, WebP и JPG; для прозрачных слоёв используйте PNG или WebP. +Все слои одной дистанции должны иметь одинаковые размеры и совмещаться +от левого верхнего угла. Один готовый спрайт — массив из одного файла. + +Необязательно задавать все дистанции: показываются только перечисленные. +Первой выбирается `normal`, затем `close`, затем `far`. Названия вариантов +внутри группы должны быть уникальны. `author` и `description` необязательны; +пустые поля не выводятся, ссылка автора поддерживает HTTP(S). +В JSON нельзя писать комментарии `//`. + +Группы доступны на `/resources/community/sprites`, участвуют в поиске, +поддерживают выбор дистанции, просмотр и скачивание собранного WebP. +Сборка и миниатюры создаются при первом обращении и кэшируются. +Изменения JSON и изображений подхватываются без перезапуска. Некорректные +дистанции пропускаются с предупреждением в журнале; при ошибке синтаксиса +JSON сохраняется предыдущий каталог. `{"groups": {}}` или удаление файла +очищает каталог. Отдельные спрайты продолжают находиться автоматически; +слои, использованные в каталоге, повторно отдельными картинками не выводятся. + ## Каталог специалистов Страница `/specialists` объединяет художников, нейрохудожников, композиторов, diff --git a/app/routes/res.py b/app/routes/res.py index 5a2c101..590edad 100644 --- a/app/routes/res.py +++ b/app/routes/res.py @@ -48,18 +48,18 @@ def _artist_img_lock(url, kind): lock = _artist_img_locks[(url, kind)] = asyncio.Lock() return lock -async def _ensure_composed(sprite): +async def _ensure_composed(sprite, community=False): - if sprite not in CONFIG.sprite_layers: + if sprite not in (CONFIG.community_sprite_layers if community else CONFIG.sprite_layers): raise HTTPException(404, f'Спрайт "{sprite}" не существует.') - if not is_composed(sprite): + if not is_composed(sprite, community): async with compose_lock: # Re-check: the request holding the lock before us may have # composed this very sprite. - if not is_composed(sprite): + if not is_composed(sprite, community): try: - await asyncio.to_thread(compose_sprite, sprite) + await asyncio.to_thread(compose_sprite, sprite, community) except Exception: logger.exception(f'Composing sprite "{sprite}" failed.') raise HTTPException(500, f'Не удалось собрать спрайт "{sprite}".') from None @@ -71,6 +71,13 @@ async def sprite_page(sprite, request: Request): return FileResponse(str(sprite_file(sprite)), media_type='image/webp', headers=cache_headers(precompressed=True)) + +@router.get('/community-sprite/{sprite}') +async def community_sprite_page(sprite: str): + await _ensure_composed(sprite, community=True) + return FileResponse(str(sprite_file(sprite, community=True)), media_type='image/webp', + headers=cache_headers(precompressed=True)) + def _find_tinted(kind, name): return next((i for collection in CONFIG.resources.values() for i in collection.get(kind, []) @@ -110,12 +117,12 @@ async def tinted_page(kind, name, request: Request): @router.get('/thumb/{kind}/{name:path}') async def thumb_page(kind, name, request: Request): - if kind not in ('bg', 'cg', 'anim', 'sprite', 'community'): + if kind not in ('bg', 'cg', 'anim', 'sprite', 'community', 'community-sprite'): raise HTTPException(404, f'Категория "{kind}" не существует.') - if kind == 'sprite': + if kind in ('sprite', 'community-sprite'): # A sprite thumb derives from the composed sprite, so compose first. - await _ensure_composed(name) + await _ensure_composed(name, community=kind == 'community-sprite') elif kind == 'community': if not any(i['file'] == name and i['thumb'] for items in CONFIG.resources.get('community', {}).values() diff --git a/app/routes/resources.py b/app/routes/resources.py index b37ad5a..9e4665c 100644 --- a/app/routes/resources.py +++ b/app/routes/resources.py @@ -83,6 +83,8 @@ def _count(category, items): # sit behind their toggle and are not part of the headline numbers. if category == 'sprites' and items and 'sprites' in items[0]: return sum(len(group['sprites']) for group in items) + if category == 'sprites': + return sum(len(item.get('variants', [item])) for item in items) return sum(1 for i in items if i['declared']) @@ -309,6 +311,14 @@ async def listing(collection, category, request: Request): present = {i['time'] for i in items} bg_times = [(key, label) for key, label in BG_TIME_LABELS.items() if key in present] + community_sprite_groups = {} + if category == 'sprites' and collection == 'community': + for item in items: + group = item.get('sprite_group') + if group: + entry = community_sprite_groups.setdefault(group['rid'], {**group, 'families': []}) + entry['families'].append(item) + return templates.TemplateResponse(request, 'resources_list.html', { 'collection': collection, 'collection_meta': COLLECTIONS[collection], @@ -317,8 +327,8 @@ async def listing(collection, category, request: Request): 'categories': switcher, 'items': items, 'count': _count(category, items), - 'count_all': (len(items) if category != 'sprites' or collection == 'community' - else sum(len(g['sprites']) for g in items)), + 'count_all': _count(category, items) if category == 'sprites' else len(items), + 'community_sprite_groups': list(community_sprite_groups.values()), 'has_undeclared': (category != 'sprites' and any(not i['declared'] for i in items)), 'other_href': other_href, diff --git a/app/utils/config.py b/app/utils/config.py index 2c0546d..caac939 100644 --- a/app/utils/config.py +++ b/app/utils/config.py @@ -212,6 +212,9 @@ def __init__(self): # Sprites are composed lazily on first request and cached on disk. self.sprite_layers = {} + # Catalogue key -> validated local layer Paths, separate from game sprites. + self.community_sprite_layers = {} + # {'original': {category: items}, 'community': {...}} from the game's # declarations and community files (see lifespan/resources_cache.py). self.resources = {} diff --git a/app/utils/lifespan/__init__.py b/app/utils/lifespan/__init__.py index bddda5c..0916c8a 100644 --- a/app/utils/lifespan/__init__.py +++ b/app/utils/lifespan/__init__.py @@ -1,5 +1,4 @@ -import asyncio -import signal +import asyncio, signal, os from contextlib import asynccontextmanager from fastapi import FastAPI @@ -137,6 +136,9 @@ async def lifespan(app: FastAPI): # restart (see refresh.py). worker = asyncio.create_task(worker_refresh_caches()) + if os.environ['ES_DOC_DEBUG'] == '1' and os.name == 'nt': + os.system('start "" "http://localhost:8000/"') + yield shutdown_livereload() diff --git a/app/utils/lifespan/community_sprites.py b/app/utils/lifespan/community_sprites.py new file mode 100644 index 0000000..6c9ab29 --- /dev/null +++ b/app/utils/lifespan/community_sprites.py @@ -0,0 +1,149 @@ +"""Local, layered community sprites declared in the assets catalogue.""" + +import hashlib +import json +import re +from pathlib import PureWindowsPath +from urllib.parse import unquote, urlsplit + +from ..config import CONFIG +from ..logging import root_logger + +logger = root_logger.getChild('lifespan').getChild('community-sprites') +DISTANCES = ('normal', 'close', 'far') +IMAGE_EXTS = {'.png', '.webp', '.jpg', '.jpeg'} + + +def layer_path(value): + """Resolve a declared image within game/ or community/, never arbitrary files.""" + if not isinstance(value, str) or not value.strip(): + raise ValueError('A layer must be a non-empty local image path') + value = value.strip() + root = CONFIG.res_path.parent / 'community' + for prefix, directory in ( + ('/resource/raw/', CONFIG.res_path), + ('/resource/community/', root), + ): + if value.startswith(prefix): + root, value = directory, unquote(value[len(prefix):]) + break + if ('\\' in value or '\x00' in value or ':' in value + or value.startswith('/') or '..' in value.split('/') + or PureWindowsPath(value).drive): + raise ValueError('Layer paths must stay inside game/ or community/') + path = (root / value).resolve() + if not path.is_relative_to(root.resolve()) or path.suffix.lower() not in IMAGE_EXTS: + raise ValueError('Layer must be an image inside game/ or community/') + if not path.is_file(): + raise ValueError(f'Layer does not exist: {value}') + return path + + +def _text(value): + return value.strip() if isinstance(value, str) else '' + + +def _layer_reference(path): + for folder, root in (('game', CONFIG.res_path), + ('community', CONFIG.res_path.parent / 'community')): + if path.is_relative_to(root.resolve()): + return folder + '/' + path.relative_to(root.resolve()).as_posix() + raise ValueError('Layer is outside the resource directories') + + +def _author(value): + value = value if isinstance(value, dict) else {} + link = _text(value.get('link')) + try: + parsed = urlsplit(link) + safe = (parsed.scheme in ('http', 'https') and parsed.netloc + and not any(c.isspace() or ord(c) < 32 for c in link)) + except ValueError: + safe = False + if not safe: + link = '' + return {'name': _text(value.get('name')), 'link': link} + + +def parse_community_sprites(): + """Return flat families plus their layer map; malformed JSON keeps the last catalogue.""" + manifest = CONFIG.res_path.parent / 'community-sprites.json' + if not manifest.exists(): + return [], {} + try: + data = json.loads(manifest.read_text('utf-8-sig')) + if not isinstance(data, dict) or not isinstance(data.get('groups'), dict): + raise TypeError('The catalogue must contain a groups object') + except (OSError, ValueError, TypeError): + logger.exception('Invalid community-sprites.json; keeping the previous catalogue.') + previous = CONFIG.resources.get('community', {}).get('sprites', []) + return [i for i in previous if i.get('sprite_group')], CONFIG.community_sprite_layers + + families, layer_map = [], {} + for title, group in data['groups'].items(): + if (not _text(title) or not isinstance(group, dict) + or not isinstance(group.get('variations'), list)): + logger.warning('Invalid sprite group %r; skipping it.', title) + continue + title = title.strip() + group_meta = { + 'title': title, 'desc': _text(group.get('description')), + 'author': _author(group.get('author')), + 'rid': 'sprite-group-' + hashlib.sha256(title.encode()).hexdigest()[:20], + } + seen = set() + for variation in group['variations']: + if not isinstance(variation, dict): + logger.warning('Invalid variation in %s; skipping it.', title) + continue + name = _text(variation.get('name')) + distances = variation.get('distances') + if not name or name in seen or not isinstance(distances, dict): + logger.warning('Invalid or duplicate variation %r in %s; skipping it.', name, title) + continue + seen.add(name) + variants = [] + layer_files = [] + for distance in DISTANCES: + if distance not in distances: + continue + try: + layers = distances[distance] + if not isinstance(layers, list) or not layers: + raise ValueError('A distance must contain at least one layer') + paths = [layer_path(layer) for layer in layers] + except (ValueError, OSError) as exc: + logger.warning('Invalid sprite %s / %s / %s: %s', title, name, distance, exc) + continue + # Include source versions so browser caches refresh too. Logical + # paths keep URLs independent of the installation directory. + versions = [(_layer_reference(p), p.stat().st_mtime_ns, p.stat().st_size) + for p in paths] + identity = json.dumps([title, name, distance, versions]) + key = hashlib.sha256(identity.encode()).hexdigest() + anchor = hashlib.sha256(json.dumps([title, name, distance]).encode()).hexdigest() + layer_map[key] = paths + layer_files.extend(paths) + filename = re.sub(r'[<>:"/\\|?*\x00-\x1f]', '_', f'{title} — {name} {distance}') + variants.append({ + 'name': filename, 'code': name, 'title': name, + 'rid': 'r-community-sprite-' + anchor, + 'distance': distance, + 'raw': f'/resource/community-sprite/{key}', + 'thumb': f'/resource/thumb/community-sprite/{key}', + }) + if not variants: + continue + primary = variants[0] + search = ' '.join([group_meta['desc'], group_meta['author']['name'], + *(f"{title} {name} {v['distance']}" for v in variants), + *(_layer_reference(p) for p in layer_files)]) + families.append({ + 'name': name, 'title': f'{title} — {name}', 'code': None, + 'file': '', 'declared': True, 'captions': [], + 'rid': primary['rid'], 'raw': primary['raw'], 'thumb': primary['thumb'], + 'desc': group_meta['desc'], 'sprite_group': group_meta, + 'variants': variants, 'primary': primary, 'search': search, + 'layer_files': layer_files, + }) + return families, layer_map diff --git a/app/utils/lifespan/refresh.py b/app/utils/lifespan/refresh.py index 48c129a..84fc1c8 100644 --- a/app/utils/lifespan/refresh.py +++ b/app/utils/lifespan/refresh.py @@ -102,6 +102,7 @@ def _watchers(): res / 'media.rpy', assets / 'descriptions.yaml', assets / 'community-descriptions.yaml', + assets / 'community-sprites.json', assets / 'nsfw.yaml', ) community_files = _under(assets / 'community') diff --git a/app/utils/lifespan/resources_cache.py b/app/utils/lifespan/resources_cache.py index 597d432..102f642 100644 --- a/app/utils/lifespan/resources_cache.py +++ b/app/utils/lifespan/resources_cache.py @@ -6,6 +6,7 @@ from ..config import CONFIG from ..logging import root_logger +from .community_sprites import parse_community_sprites logger = root_logger.getChild('lifespan').getChild('resources-cache') @@ -706,7 +707,7 @@ def _build_search_items(collection, collection_name='original'): } if collection_name == 'community': row['context'] = 'Ресурсы сообщества / ' + row['context'] - row['keywords'] = ' '.join([item['file'], *item.get('captions', [])]) + row['keywords'] = ' '.join([item['file'], item.get('search', ''), *item.get('captions', [])]) # Real descriptions (auto bg/music or hand-written) are searchable # too; the "уточняется" placeholder would only add noise. if item['desc'] and item['desc'] not in (PLACEHOLDER_DESC, UNDECLARED_DESC): @@ -731,11 +732,18 @@ def parse_resources(): # Community files are independent of the game's Ren'Py declarations. community_root = CONFIG.res_path.parent / 'community' community = _parse_community(community_root, _load_community_descriptions()) + custom_sprites, custom_layers = parse_community_sprites() + used_layers = {path for item in custom_sprites for path in item['layer_files']} + community['sprites'] = custom_sprites + [ + item for item in community['sprites'] + if (community_root / item['file']).resolve() not in used_layers + ] # NSFW CG declarations are cut from the original collection and are not # listed in the community collection either. original['cg'] = [i for i in original['cg'] if not i['nsfw']] + CONFIG.community_sprite_layers = custom_layers CONFIG.resources = {'original': original, 'community': community} # Merged into CONFIG.search_items at startup and after assets refreshes. CONFIG.resource_search_items = ( diff --git a/app/utils/lifespan/sprites_cache.py b/app/utils/lifespan/sprites_cache.py index a00cac2..eb837a3 100644 --- a/app/utils/lifespan/sprites_cache.py +++ b/app/utils/lifespan/sprites_cache.py @@ -35,16 +35,17 @@ def parse_sprites(): CONFIG.sprite_layers = sprites logger.info(f'{len(sprites)} sprite combinations found.') -def sprite_file(name): - return sprites_path() / f'{name}.webp' +def sprite_file(name, community=False): + root = CONFIG.cache_path / 'community-sprites' if community else sprites_path() + return root / f'{name}.webp' -def is_composed(name): +def is_composed(name, community=False): # Both the declaration and every layer contribute to the composed bytes. - path = sprite_file(name) - layers = CONFIG.sprite_layers.get(name) + path = sprite_file(name, community) + layers = (CONFIG.community_sprite_layers if community else CONFIG.sprite_layers).get(name) if not path.is_file() or not layers: return False - sources = [p for p in _sprite_sources() if p.exists()] + sources = [] if community else [p for p in _sprite_sources() if p.exists()] sources.extend(CONFIG.res_path / layer for layer in layers) try: newest = max(source.stat().st_mtime_ns for source in sources) @@ -52,9 +53,9 @@ def is_composed(name): except OSError: return False -def compose_sprite(name): +def compose_sprite(name, community=False): - layers = CONFIG.sprite_layers[name] + layers = (CONFIG.community_sprite_layers if community else CONFIG.sprite_layers)[name] starttime = time.time() @@ -63,11 +64,14 @@ def compose_sprite(name): for layer in layers[1:]: with Image.open(CONFIG.res_path / layer) as overlay: + if community and overlay.size != img.size: + raise ValueError('All layers of a community sprite must have the same dimensions') img.alpha_composite(overlay.convert('RGBA')) # Write to a temp name and swap it in, so a request that arrives while a # compose is in flight never sees a half-written file. - path = sprite_file(name) + path = sprite_file(name, community) + path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix('.webp.tmp') img.save(tmp, 'WEBP', quality=CONFIG.setting('images.sprite-quality')) os.replace(tmp, path) diff --git a/app/utils/lifespan/thumbs_cache.py b/app/utils/lifespan/thumbs_cache.py index 363378f..a38df30 100644 --- a/app/utils/lifespan/thumbs_cache.py +++ b/app/utils/lifespan/thumbs_cache.py @@ -28,6 +28,8 @@ def _source_file(kind, name): # or the community drop-in folder next to it. if kind == 'sprite': return sprite_file(name) + if kind == 'community-sprite': + return sprite_file(name, community=True) if name in CONFIG.community_sprite_layers else None if kind == 'community': listed = any(i['file'] == name and i['thumb'] for category in CONFIG.resources.get('community', {}).values() diff --git a/docs/plans/2026-10-16-community-sprites.md b/docs/plans/2026-10-16-community-sprites.md new file mode 100644 index 0000000..de82145 --- /dev/null +++ b/docs/plans/2026-10-16-community-sprites.md @@ -0,0 +1,31 @@ +# Пользовательские спрайты + +**Цель:** каталог `community-sprites.json` в es-doc-assets с форматом +`groups → variations → distances → [слои]`, предложенным пользователем. + +**Решение:** сохранить плоский список ресурсов сообщества, добавив записи +вариантов с метаданными группы и дистанциями. Показывать их в группах на +существующей странице спрайтов. Отдельные изображения остаются совместимыми; +слои, используемые каталогом, не выводятся повторно отдельными спрайтами. +Автор и описание принадлежат группе. Используется существующий выбор дистанции. + +**Пути:** пользователь подтвердил только локальные файлы es-doc-assets. +Относительный путь считается от community/. `/resource/raw/` адресует game/, +`/resource/community/` адресует community/. Выход за пределы этих папок запрещён. +Слои одной дистанции имеют одинаковые размеры и накладываются в порядке массива. + +**План реализации:** + +1. Добавить интеграционные тесты загрузки JSON, групп, поиска, порядка слоёв, + дистанций, безопасности путей, обновления кэша и совместимости одиночных файлов. + Запустить и подтвердить отсутствие новой функциональности. +2. Добавить загрузчик каталога и карту слоёв в CONFIG. Некорректные записи + пропускать с предупреждением; при повреждённом JSON сохранять прежний каталог. +3. Расширить существующий конвейер сборки и миниатюр отдельным пространством + кэша и маршрутами пользовательских спрайтов. Обновлять при изменении слоёв. +4. Добавить группировку на странице, автора и описание, переиспользуя выбор + дистанции, просмотр, скачивание, фильтрацию и поиск. +5. Добавить документацию и пустой каталог в репозиторий ассетов. Запустить + Python- и JavaScript-тесты, проверки синтаксиса и diff; проверить страницу. + +**Технологии:** Python / FastAPI / Pillow, Jinja, существующий JavaScript. diff --git a/static/css/player.css b/static/css/player.css index e5c5e56..6b27ed8 100644 --- a/static/css/player.css +++ b/static/css/player.css @@ -178,7 +178,7 @@ flex-shrink: 0; } -.res-nowplaying--ended .res-nowplaying-repeat { +.res-nowplaying--ended:not(.res-nowplaying--local) .res-nowplaying-repeat { color: var(--accent); } @@ -294,6 +294,16 @@ } } +@media (max-width: 30em) { + .res-nowplaying .res-volume { + flex: 1; + } + + .res-nowplaying .res-volume input { + min-width: 0; + } +} + /* ── Reduced motion ──────────────────────────────────────── */ @media (prefers-reduced-motion: reduce) { diff --git a/static/css/tools.css b/static/css/tools.css index 1bb5370..542842e 100644 --- a/static/css/tools.css +++ b/static/css/tools.css @@ -45,6 +45,7 @@ .tools-export-dialog { width: min(42rem, calc(100% - 32px)); max-height: calc(100dvh - 32px); box-sizing: border-box; padding: 24px; border: 0; border-radius: var(--radius-block); background: var(--bg-elevated); color: var(--text); box-shadow: var(--shadow-modal); overflow-y: auto; scrollbar-color: var(--border) var(--bg-elevated); } .tools-export-dialog::backdrop { background: var(--scrim); } html:has(.tools-export-dialog[open]) { overflow: hidden; } +html:has(.tools-code-dialog[open]) { overflow: hidden; } .tools-dialog-heading { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 20px; } .tools-dialog-heading h2 { margin: 0; font-family: var(--font-serif); font-size: var(--fs-subtitle); } .tools-dialog-close { display: inline-flex; align-items: center; justify-content: center; flex: none; width: 44px; height: 44px; padding: 0; border: 0; border-radius: var(--radius-sm); background: none; color: var(--text-soft); cursor: pointer; } @@ -180,13 +181,28 @@ html:has(.tools-export-dialog[open]) { overflow: hidden; } .tools-browser-preview h4 { margin: 0 0 14px; font-size: var(--fs-ui); overflow-wrap: anywhere; } .tools-preview-heading h4 { margin: 0; } .tools-browser-preview img, .tools-browser-preview video { display: block; max-width: 100%; max-height: 380px; object-fit: contain; margin-bottom: 14px; } -.tools-browser-preview audio { display: block; width: 100%; margin-bottom: 14px; } -.tools-code-frame { margin-bottom: 16px; } -.tools-code-frame pre { max-height: 440px; overflow-y: auto; margin: 0; font-size: var(--fs-ui); line-height: var(--lh-ui); align-items: flex-start; } +.tools-code-frame { display: flex; flex-direction: column; margin-bottom: 16px; min-width: 0; border: 1px solid var(--border); border-radius: var(--radius-block); background: var(--code-bg); transform-origin: top left; } +.tools-code-toolbar { display: flex; flex: none; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 4px 8px 4px 16px; border-bottom: 1px solid var(--border); } +.tools-code-toolbar .tools-preview-heading { flex: 1; min-width: 0; margin: 0; } +.tools-code-toolbar h4 { display: flex; align-items: center; min-height: 44px; margin: 0; font: 600 var(--fs-ui)/var(--lh-ui) var(--font-sans); overflow-wrap: anywhere; } +.tools-code-actions { display: flex; flex: none; align-items: center; gap: 4px; } +.tools-code-actions :is(.code-copy, .tools-code-expand) { position: static; display: inline-flex; align-items: center; justify-content: center; flex: none; width: 44px; height: 44px; padding: 0; border: 0; border-radius: var(--radius-sm); color: var(--text-soft); background: transparent; cursor: pointer; } +.tools-code-actions :is(.code-copy, .tools-code-expand):hover { color: var(--text); background: var(--bg-light); } +.tools-code-actions :is(.code-copy, .tools-code-expand):focus-visible { outline: var(--focus-ring); outline-offset: -2px; } +.tools-code-actions .code-copy.copied { color: var(--code-success); } +.tools-code-frame pre { max-height: 440px; min-height: 0; overflow: auto; margin: 0; border: 0; border-radius: 0 0 var(--radius-block) var(--radius-block); font-size: var(--fs-ui); line-height: var(--lh-ui); align-items: flex-start; scrollbar-color: var(--border) var(--code-bg); } .tools-code-frame pre:focus-visible { outline: var(--focus-ring); outline-offset: -2px; } -/* Keep both columns at their content height. Stretching the code column to - the capped pre creates another vertical scrollport and detaches its rows - from the gutter. The pre owns vertical scroll; code-scroll owns horizontal. */ +/* One viewport for both axes keeps the horizontal scrollbar visible even + at the top of a long file, and the line numbers aligned with the code. */ +.tools-code-frame .code-scroll { flex: 0 0 auto; min-width: 0; overflow: visible; background: none; } +.tools-code-frame code { white-space: pre; overflow-wrap: normal; } +.tools-code-placeholder { display: block; margin-bottom: 16px; } +.tools-code-dialog { width: 100%; max-width: none; height: 100%; height: 100dvh; max-height: none; margin: 0; padding: 0; border: 0; border-radius: 0; overflow: hidden; background: transparent; color: var(--text); } +.tools-code-dialog[open] { display: flex; flex-direction: column; } +.tools-code-dialog::backdrop { background: transparent; } +.tools-code-content { flex: 1; min-height: 0; min-width: 0; display: flex; } +.tools-code-content .tools-code-frame { width: 100%; min-width: 0; margin: 0; border: 0; border-radius: 0; } +.tools-code-content pre { flex: 1; width: 100%; max-height: none; border-radius: 0; } .tools-preview-pending { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; min-height: 260px; } .tools-browser-preview .tools-preview-pending > p { margin: 0; color: var(--text-soft); } .tools-browser-preview .tools-preview-empty { display: flex; justify-content: center; align-items: center; min-height: 260px; margin: 0; color: var(--text-soft); } diff --git a/static/icons/manifest.json b/static/icons/manifest.json index 8bc0f94..6cc16e1 100644 --- a/static/icons/manifest.json +++ b/static/icons/manifest.json @@ -29,6 +29,8 @@ "layout-grid", "lightbulb", "list", + "maximize-2", + "minimize-2", "moon", "music", "octagon-alert", @@ -38,6 +40,7 @@ "play", "redo-2", "repeat", + "repeat-1", "rotate-ccw", "search", "send", diff --git a/static/icons/maximize-2.svg b/static/icons/maximize-2.svg new file mode 100644 index 0000000..790d253 --- /dev/null +++ b/static/icons/maximize-2.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/static/icons/minimize-2.svg b/static/icons/minimize-2.svg new file mode 100644 index 0000000..f15d72c --- /dev/null +++ b/static/icons/minimize-2.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/static/icons/repeat-1.svg b/static/icons/repeat-1.svg new file mode 100644 index 0000000..4b7fa56 --- /dev/null +++ b/static/icons/repeat-1.svg @@ -0,0 +1,17 @@ + + + + + + + diff --git a/static/js/icons.js b/static/js/icons.js index 67ceb7b..8199b0d 100644 --- a/static/js/icons.js +++ b/static/js/icons.js @@ -30,6 +30,8 @@ "layout-grid": "\n \n \n ", "lightbulb": "\n \n ", "list": "\n \n \n \n \n ", + "maximize-2": "\n \n \n ", + "minimize-2": "\n \n \n ", "moon": "", "music": "\n \n ", "octagon-alert": "\n \n ", @@ -39,6 +41,7 @@ "play": "", "redo-2": "\n ", "repeat": "\n \n \n ", + "repeat-1": "\n \n \n \n ", "rotate-ccw": "\n ", "search": "\n ", "send": "\n ", diff --git a/static/js/player.js b/static/js/player.js index c8721e4..1d77df2 100644 --- a/static/js/player.js +++ b/static/js/player.js @@ -44,6 +44,8 @@ let current = null; let currentSrc = ''; let currentName = ''; + let localTrack = null; + let localRepeat = 'off'; let resumeTime = 0; let finished = false; @@ -96,15 +98,19 @@ (button.dataset.playLabel || `Прослушать ${button.dataset.playName || 'аудиофайл'}`)); }; - const setRepeat = enabled => { - audio.loop = enabled; + const repeatLabels = { off: 'Повтор выключен', track: 'Повтор трека', queue: 'Повтор очереди' }; + const setRepeat = mode => { + const enabled = mode !== 'off'; + audio.loop = mode === 'track'; repeat.setAttribute('aria-pressed', enabled ? 'true' : 'false'); - repeat.setAttribute('aria-label', enabled ? 'Повтор включён' : 'Повтор выключен'); - repeat.title = enabled ? 'Выключить повтор' : 'Повторить произведение'; + const label = localTrack ? repeatLabels[mode] : enabled ? 'Повтор включён' : repeatLabels.off; + repeat.setAttribute('aria-label', label); + repeat.title = localTrack ? label : enabled ? 'Выключить повтор' : 'Повторить произведение'; + repeat.innerHTML = window.ESDocIcons.svg(localTrack && mode === 'track' ? 'repeat-1' : 'repeat', 18); }; const persist = (playing = !audio.paused, time = audio.currentTime) => { - if (!currentSrc) return; + if (!currentSrc || localTrack) return; writePlayerState(playerStorage, { src: currentSrc, name: currentName, @@ -165,19 +171,26 @@ barVolume.addEventListener('input', () => setVolume(parseFloat(barVolume.value))); const stop = () => { - audio.pause(); if (current && bar.contains(document.activeElement)) current.focus(); - bar.classList.remove('res-nowplaying--visible', 'res-nowplaying--ended'); + bar.classList.remove('res-nowplaying--visible', 'res-nowplaying--ended', 'res-nowplaying--local'); setButtonState(current, false); current = null; currentSrc = ''; currentName = ''; + resumeTime = 0; finished = false; + audio.pause(); + if (localTrack) { + localTrack = null; + audio.removeAttribute('src'); + audio.load(); + } clearPlayerState(playerStorage); }; const finish = () => { - if (audio.loop) return; + if (!currentSrc || audio.loop) return; + if (localTrack?.advance(localRepeat === 'queue')) return; finished = true; audio.currentTime = 0; setButtonState(current, false); @@ -189,24 +202,38 @@ }; audio.addEventListener('ended', finish); - audio.addEventListener('error', stop); - bar.querySelector('.res-nowplaying-stop').addEventListener('click', stop); + audio.addEventListener('error', () => { + if (!audio.error) return; + localTrack?.onError(); + stop(); + }); + bar.querySelector('.res-nowplaying-stop').addEventListener('click', () => { + if (bar.contains(document.activeElement)) localTrack?.restoreFocus(); + stop(); + }); - pause.addEventListener('click', () => { + const togglePlayback = () => { if (audio.paused) { if (finished) { audio.currentTime = 0; finished = false; } audio.play().catch(() => {}); } else { audio.pause(); } - }); + }; + pause.addEventListener('click', togglePlayback); repeat.addEventListener('click', () => { - setRepeat(!audio.loop); + if (localTrack) { + localRepeat = { off: 'track', track: 'queue', queue: 'off' }[localRepeat]; + setRepeat(localRepeat); + } else { + setRepeat(audio.loop ? 'off' : 'track'); + } persist(!audio.paused); }); audio.addEventListener('pause', () => { + if (!currentSrc || !audio.paused) return; bar.classList.add('res-nowplaying--paused'); pause.setAttribute('aria-label', 'Продолжить'); setButtonState(current, false); @@ -215,6 +242,7 @@ }); audio.addEventListener('play', () => { + if (!currentSrc || audio.paused) return; finished = false; bar.classList.remove('res-nowplaying--paused', 'res-nowplaying--ended'); pause.setAttribute('aria-label', 'Пауза'); @@ -223,6 +251,38 @@ status.textContent = 'Воспроизведение: ' + (barName.textContent || '') + '.'; }); + const startTrack = (src, name, button = null, track = null) => { + stop(); + current = button; + currentSrc = src; + currentName = name; + localTrack = track; + barName.textContent = currentName; + barName.title = currentName; + seek.value = 0; + seek.max = 0; + setFill(seek); + timeNow.textContent = timeAll.textContent = '0:00'; + setRepeat(track ? localRepeat : 'off'); + if (track) bar.classList.add('res-nowplaying--local'); + pause.setAttribute('aria-label', 'Воспроизвести'); + bar.classList.add('res-nowplaying--visible', 'res-nowplaying--paused'); + audio.src = currentSrc; + audio.play().catch(error => { + if (track && localTrack === track && error.name === 'NotAllowedError') { + status.textContent = 'Нажмите кнопку воспроизведения в плеере.'; + } + }); + }; + + // Local previews own their object URLs and release them after stopping playback. + window.ESDocPlayer = { + playLocal: track => startTrack(track.src, track.name, null, track), + stopLocal: src => { + if (localTrack?.src === src) stop(); + }, + }; + const bindButtons = () => { document.querySelectorAll('[data-player-fallback]').forEach(el => el.remove()); buttons = [...document.querySelectorAll('[data-play-src]')]; @@ -232,30 +292,11 @@ button.dataset.playerBound = '1'; button.hidden = false; button.addEventListener('click', () => { - if (current === button) { - if (audio.paused) { - if (finished) audio.currentTime = 0; - audio.play().catch(() => {}); - } else { - audio.pause(); + if (current === button) { + togglePlayback(); + return; } - return; - } - - stop(); - current = button; - currentSrc = button.dataset.playSrc; - currentName = button.dataset.playName || ''; - barName.textContent = currentName; - seek.value = 0; - seek.max = 0; - setFill(seek); - timeNow.textContent = timeAll.textContent = '0:00'; - finished = false; - setRepeat(false); - bar.classList.add('res-nowplaying--visible'); - audio.src = currentSrc; - audio.play().catch(() => {}); + startTrack(button.dataset.playSrc, button.dataset.playName || '', button); }); }); }; @@ -269,7 +310,7 @@ currentName = saved.name; barName.textContent = currentName; resumeTime = saved.time; - setRepeat(saved.repeat); + setRepeat(saved.repeat ? 'track' : 'off'); bar.classList.add('res-nowplaying--visible'); audio.src = saved.src; if (saved.playing) audio.play().catch(() => persist(false, saved.time)); diff --git a/static/js/resources.js b/static/js/resources.js index af6c509..3f41cbe 100644 --- a/static/js/resources.js +++ b/static/js/resources.js @@ -139,6 +139,7 @@ const raw = option.dataset.raw || ''; const thumb = option.dataset.thumb || ''; const file = option.dataset.file || ''; + const label = option.dataset.label || code; name.textContent = code; distance.textContent = option.dataset.distance; @@ -146,9 +147,9 @@ if (imageLink && image && raw && thumb) { imageLink.href = raw; - imageLink.dataset.zoom = code; + imageLink.dataset.zoom = label; imageLink.dataset.file = file; - imageLink.setAttribute('aria-label', `Открыть «${code}» в полном размере`); + imageLink.setAttribute('aria-label', `Открыть «${label}» в полном размере`); image.src = thumb; image.alt = ''; } @@ -229,7 +230,7 @@ row.addEventListener('res:sprite-filter', event => { const query = event.detail.query; const match = query - ? options.find(option => option.dataset.code.toLowerCase().includes(query)) + ? options.find(option => `${option.dataset.code} ${option.dataset.distance}`.toLowerCase().includes(query)) : options[0]; if (match) { select(match); diff --git a/static/js/tools-core.js b/static/js/tools-core.js index e63025b..c78a0c4 100644 --- a/static/js/tools-core.js +++ b/static/js/tools-core.js @@ -64,7 +64,13 @@ const normalized = (source?.[2] || technical).replace(/\s+/g, ' ').trim(); const version = normalized.match(/generated by ren'?py version (\d+) or below/i); let title, explanation; - if (/Контейнер: Python-блок.*байткод/i.test(normalized)) { + if (/Декомпиляция пропущена: файл сценария превышает 128 МиБ/i.test(normalized)) { + title = 'Исходный файл сценария слишком большой для декомпиляции'; + explanation = 'Оригинальный .rpyc/.rpymc/.pyc сохранён в ZIP без изменений. Создание исходного .rpy/.rpym пропущено, чтобы не исчерпать память браузера.'; + } else if (/Декомпиляция пропущена: распакованные данные сценария превышают 256 МиБ/i.test(normalized)) { + title = 'Сценарий слишком большой для декомпиляции'; + explanation = 'Оригинальный файл сохранён в ZIP без изменений. Создание исходного .rpy/.rpym пропущено, чтобы не исчерпать память браузера.'; + } else if (/Контейнер: Python-блок.*байткод/i.test(normalized)) { title = 'Python-блок восстановлен частично'; explanation = 'Исходный Python-код не восстановлен: в файле сохранился только байткод. На месте блока оставлены комментарий и pass. Для работы сценария этот код потребуется восстановить отдельно.'; } else if (/Контейнер:.*не восстановлен/i.test(normalized)) { @@ -105,7 +111,13 @@ let title = 'Не удалось обработать файл'; let explanation = 'Попробуйте открыть файл ещё раз. Если ошибка повторяется, выберите другой файл из папки игры. Техническое сообщение ниже поможет разобраться в причине.'; let tryHarder = false; - if (/PYC:.*Python.*не поддерживается/i.test(normalized)) { + if (/LIMIT_RPA_INDEX_COMPRESSED|LIMIT_RPA_INDEX_EXPANDED|LIMIT_RPA_INDEX_ENTRIES|LIMIT_RPA_INDEX_SEGMENTS/i.test(normalized)) { + title = 'Слишком большое оглавление архива'; + explanation = 'В архиве слишком много файлов или его оглавление превышает допустимый размер. ES Doc не стал обрабатывать этот архив, чтобы браузер не завис. Попробуйте другой архив.'; + } else if (/LIMIT_DECOMPILED_DATA/i.test(normalized)) { + title = 'Сценарий слишком велик для декомпиляции'; + explanation = 'Распакованные данные сценария превышают допустимый размер. При обработке архива исходный .rpyc сохранится, но файл .rpy создан не будет.'; + } else if (/PYC:.*Python.*не поддерживается/i.test(normalized)) { title = 'Версия Python не поддерживается' explanation = 'Декомпиляция PYC доступна для байткода Python 2.0–3.8. Этот файл создан другой версией Python. В ZIP сохранится оригинал .pyc.' } else if (/PYC:/i.test(normalized)) { diff --git a/static/js/tools.js b/static/js/tools.js index 2a001c3..3678093 100644 --- a/static/js/tools.js +++ b/static/js/tools.js @@ -31,6 +31,62 @@ const queuePrevious = get('queue-previous'), queueNext = get('queue-next'); const controller = new AbortController(); const on = (element, event, callback) => element.addEventListener(event, callback, { signal: controller.signal }); + const codeDialog = get('code-dialog'), codeContent = get('code-content'); + let expandedCode = null; + const setCodeExpanded = (button, expanded) => { + const label = expanded ? 'Свернуть' : 'На весь экран'; + button.innerHTML = window.ESDocIcons.svg(expanded ? 'minimize-2' : 'maximize-2', 18); + button.title = label; + button.setAttribute('aria-label', label); + button.setAttribute('aria-expanded', String(expanded)); + }; + const restoreCode = () => { + if (!expandedCode) return; + const { frame, pre, button, position, animation } = expandedCode; + expandedCode = null; + animation?.cancel(); + const top = pre.scrollTop, left = pre.scrollLeft; + position.replaceWith(frame); + pre.scrollTop = top; + pre.scrollLeft = left; + setCodeExpanded(button, false); + }; + const animateCode = (from, to, duration, finish = () => {}) => { + const state = expandedCode; + state.animation?.cancel(); + if (!state.frame.animate) { finish(); return; } + const base = state.frame.getBoundingClientRect(); + const transform = rect => `translate(${rect.left - base.left}px, ${rect.top - base.top}px) scale(${rect.width / base.width}, ${rect.height / base.height})`; + const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches; + const animation = state.frame.animate(reduced + ? [{ opacity: 0.8 }, { opacity: 1 }] + : [{ transform: transform(from) }, { transform: transform(to) }], + { duration: reduced ? 80 : duration, easing: 'cubic-bezier(0.16, 1, 0.3, 1)', fill: 'both' }); + state.animation = animation; + animation.finished.then(() => { + if (expandedCode !== state || state.animation !== animation) return; + animation.cancel(); + state.animation = null; + finish(); + }).catch(() => {}); // A new transition or cleanup cancels the old one. + }; + const closeCode = (animate = true) => { + if (animate && expandedCode) { + if (expandedCode.closing) return; + expandedCode.closing = true; + animateCode(expandedCode.frame.getBoundingClientRect(), expandedCode.position.getBoundingClientRect(), 180, () => closeCode(false)); + return; + } + const button = expandedCode?.button; + restoreCode(); + if (codeDialog.open) codeDialog.close(); + button?.focus({ preventScroll: true }); + }; + on(codeDialog, 'cancel', event => { + event.preventDefault(); + closeCode(); + }); + on(codeDialog, 'close', restoreCode); const modeFiles = { pack: new Map(), unpack: new Map() }; let files = modeFiles[mode]; const rows = new Map(); @@ -41,6 +97,7 @@ const outputs = []; let browseEntries = [], browseFolder = '', browseRequest = 0, previewUrl = null; let catalogEntries = [], catalogFiles = [], catalogRequest = 0, selectedEntry = null; + let selectedAudioEntries = []; let task = '', exportReady = false, catalogSubmitted = false, previewFont = null, clearOnDownload = false; let packDownloadStarted = false, exportFinished = false; let operation = 0; @@ -75,7 +132,17 @@ exportStatus.textContent = 'Скачивание запущено.'; exportStatus.classList.remove('is-error'); }; + const releasePreview = () => { + if (previewUrl) { + window.ESDocPlayer?.stopLocal(previewUrl); + URL.revokeObjectURL(previewUrl); + } + if (previewFont) document.fonts.delete(previewFont); + previewFont = null; + previewUrl = null; + }; const clearResult = () => { + closeCode(false); exportFinished = false; if (exportDialog.open) exportDialog.close(); task = ''; @@ -90,15 +157,13 @@ pendingPreviewKey = ''; catalogRequest++; browseRequest++; - if (previewUrl) URL.revokeObjectURL(previewUrl); - if (previewFont) document.fonts.delete(previewFont); - previewFont = null; - previewUrl = null; + releasePreview(); browseEntries = []; catalogEntries = []; catalogFiles = []; catalogSubmitted = false; selectedEntry = null; + selectedAudioEntries = []; exportReady = false; clearOnDownload = false; if (mode !== 'pack') browseFolder = ''; @@ -466,11 +531,14 @@ if (files.size) loadCatalog(); else say(mode === 'pack' ? 'Добавьте файлы для нового RPA-архива.' : 'Добавьте архивы или скомпилированные скрипты.'); }); - const readBrowse = entry => { + const audioTypes = { ogg: 'audio/ogg', mp3: 'audio/mpeg', wav: 'audio/wav', opus: 'audio/ogg', flac: 'audio/flac' }; + const extensionOf = path => path.split('.').pop().toLowerCase(); + const readBrowse = (entry, audioEntries = selectedEntry === entry ? selectedAudioEntries : []) => { if (busy) return; retryAvailable = false; say(''); selectedEntry = entry; + selectedAudioEntries = audioEntries; const previewOptions = options(); const cacheKey = JSON.stringify([entry.id, previewOptions]); for (const button of browserList.querySelectorAll('[data-entry-id]')) { @@ -503,10 +571,7 @@ pending.textContent = /\.(rpyc|rpymc|pyc)$/i.test(entry.path) ? 'Декомпилируем файл…' : 'Открываем файл…'; previewPending.appendChild(pending); browserPreview.appendChild(previewPending); - if (previewUrl) URL.revokeObjectURL(previewUrl); - if (previewFont) document.fonts.delete(previewFont); - previewFont = null; - previewUrl = null; + releasePreview(); browserStatus.textContent = ''; updateControls(); try { @@ -577,6 +642,7 @@ }; const folderNames = [...folders].sort((a, b) => a.localeCompare(b, 'ru')); if (mode === 'pack') entries.sort((a, b) => a.path.localeCompare(b.path, 'ru')); + const audioEntries = entries.filter(entry => Object.hasOwn(audioTypes, extensionOf(entry.path))); queueMatches = folderNames.length + entries.length; const pageSize = mode === 'pack' ? queuePageSize : 500; queuePage = Math.min(queuePage, Math.max(0, Math.ceil(queueMatches / pageSize) - 1)); @@ -623,7 +689,7 @@ const kind = /\.(rpyc|rpymc|pyc|rpy|rpym|py|js|json|css|txt)$/i.test(entry.path) ? 'code' : /\.(png|jpg|jpeg|gif|webp|svg)$/i.test(entry.path) ? 'image' : /\.(ogg|mp3|wav|opus|flac|mp4|webm)$/i.test(entry.path) ? 'media' : 'file'; - row(query ? entry.path : entry.path.slice(browseFolder.length), size(entry.size), () => readBrowse(entry), kind, + row(query ? entry.path : entry.path.slice(browseFolder.length), size(entry.size), () => readBrowse(entry, audioEntries), kind, selectedEntry?.id === entry.id, entry.id); if (mode === 'pack' || catalogFiles[entry.source]?.path === entry.path && !isArchive(catalogFiles[entry.source]) && files.has(entry.path)) { addRemove([mode === 'pack' ? entry.originalPath : entry.path], 'Убрать ' + entry.path, 'Убрать файл'); @@ -699,13 +765,11 @@ } }; const showPreview = data => { - if (previewUrl) URL.revokeObjectURL(previewUrl); - if (previewFont) document.fonts.delete(previewFont); - previewFont = null; + releasePreview(); const path = data.name; - const extension = path.split('.').pop().toLowerCase(); + const extension = extensionOf(path); const mime = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp', gif: 'image/gif', - svg: 'image/svg+xml', ogg: 'audio/ogg', mp3: 'audio/mpeg', wav: 'audio/wav', opus: 'audio/ogg', flac: 'audio/flac', + svg: 'image/svg+xml', ...audioTypes, mp4: 'video/mp4', webm: 'video/webm', ttf: 'font/ttf', otf: 'font/otf', woff: 'font/woff', woff2: 'font/woff2' }[extension] || 'application/octet-stream'; previewUrl = URL.createObjectURL(data.file || new Blob([data.buffer], { type: mime })); browserPreview.replaceChildren(); @@ -731,8 +795,8 @@ img.src = previewUrl; img.alt = path; browserPreview.appendChild(img); - } else if (mime.startsWith('audio/') || mime.startsWith('video/')) { - const media = document.createElement(mime.startsWith('audio/') ? 'audio' : 'video'); + } else if (mime.startsWith('video/')) { + const media = document.createElement('video'); media.controls = true; media.preload = 'metadata'; media.src = previewUrl; @@ -769,9 +833,14 @@ copy.title = 'Скопировать код'; copy.setAttribute('aria-label', 'Скопировать код'); // Same copy/check icons and shared CSS as fenced code blocks. - copy.innerHTML = window.ESDocIcons.svg('copy', 14) + window.ESDocIcons.svg('check', 14); + copy.innerHTML = window.ESDocIcons.svg('copy', 18) + window.ESDocIcons.svg('check', 18); const frame = document.createElement('div'); frame.className = 'code-block code-block--numbered tools-code-frame'; + const toolbar = document.createElement('div'); + toolbar.className = 'tools-code-toolbar'; + const actions = document.createElement('div'); + actions.className = 'tools-code-actions'; + toolbar.append(heading, actions); const pre = document.createElement('pre'); pre.tabIndex = 0; pre.setAttribute('aria-label', 'Код файла'); @@ -782,13 +851,12 @@ gutter.textContent = lines.map((_, i) => String(i + 1)).join('\n'); const scroll = document.createElement('span'); scroll.className = 'code-scroll'; - // Focus the bounded viewport, not its very tall code column: - // focusing that column can scroll the panel halfway through a file. + // Keep keyboard navigation on the viewport shared by both axes. pre.addEventListener('keydown', event => { if (event.target !== pre || event.altKey || event.ctrlKey || event.metaKey) return; if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return; event.preventDefault(); - scroll.scrollLeft += event.key === 'ArrowRight' ? 40 : -40; + pre.scrollLeft += event.key === 'ArrowRight' ? 40 : -40; }); const code = document.createElement('code'); // Only HTML escaped by our local Pygments formatter is inserted. @@ -796,13 +864,37 @@ else code.textContent = text; scroll.appendChild(code); pre.append(gutter, scroll); - frame.appendChild(pre); + frame.append(toolbar, pre); if (window.copyControl && window.navigator?.clipboard) { copy.addEventListener('click', window.copyControl(copy, () => text, { message: 'Код скопирован.', status: browserStatus })); - frame.appendChild(copy); + actions.appendChild(copy); } + const expand = document.createElement('button'); + expand.type = 'button'; + expand.className = 'tools-code-expand'; + setCodeExpanded(expand, false); + expand.setAttribute('aria-haspopup', 'dialog'); + expand.setAttribute('aria-controls', 'tools-code-dialog'); + expand.addEventListener('click', () => { + if (expandedCode) { closeCode(); return; } + const position = document.createElement('span'); + position.className = 'tools-code-placeholder'; + const rect = frame.getBoundingClientRect(); + position.style.height = rect.height + 'px'; + const top = pre.scrollTop, left = pre.scrollLeft; + frame.before(position); + expandedCode = { frame, pre, button: expand, position }; + setCodeExpanded(expand, true); + codeContent.appendChild(frame); + codeDialog.showModal(); + pre.scrollTop = top; + pre.scrollLeft = left; + expand.focus({ preventScroll: true }); + animateCode(rect, frame.getBoundingClientRect(), 260); + }); + actions.appendChild(expand); browserPreview.appendChild(frame); - } else { + } else if (!mime.startsWith('audio/')) { const note = document.createElement('p'); note.textContent = 'Предпросмотр для этого формата недоступен.'; browserPreview.appendChild(note); @@ -815,14 +907,34 @@ browserPreview.appendChild(link); browserPreview.setAttribute('aria-busy', 'false'); browserStatus.textContent = ''; + if (mime.startsWith('audio/')) { + const queue = selectedAudioEntries; + const index = queue.indexOf(selectedEntry); + const entryId = selectedEntry?.id; + window.ESDocPlayer.playLocal({ + src: previewUrl, + name: path, + advance: wrap => { + if (busy || disposed || index < 0) return false; + const next = queue[index + 1] || (wrap ? queue[0] : null); + if (!next) return false; + readBrowse(next, queue); + return true; + }, + onError: () => { browserStatus.textContent = 'Не удалось воспроизвести аудиофайл.'; }, + restoreFocus: () => { + const row = [...browserList.querySelectorAll('[data-entry-id]')] + .find(button => button.dataset.entryId === entryId); + (row && !row.disabled ? row : link).focus(); + }, + }); + } }; const openBrowse = () => { selectedEntry = null; + selectedAudioEntries = []; browseRequest++; - if (previewUrl) URL.revokeObjectURL(previewUrl); - if (previewFont) document.fonts.delete(previewFont); - previewFont = null; - previewUrl = null; + releasePreview(); const source = Number(browseArchive.value) || 0; const scripts = browseArchive.value === 'scripts'; browseEntries = mode === 'pack' ? catalogEntries : catalogEntries.filter(entry => scripts diff --git a/static/tools/engine.py b/static/tools/engine.py index 39bf751..fbfb19f 100644 --- a/static/tools/engine.py +++ b/static/tools/engine.py @@ -19,6 +19,16 @@ CHUNK = 256 * 1024 MAX_PREVIEW_BYTES = 64 * 1024 * 1024 +MAX_DECOMPILE_INPUT_BYTES = 128 * 1024 * 1024 +MAX_DECOMPILED_DATA_BYTES = 256 * 1024 * 1024 +MAX_COMPRESSED_RPA_INDEX_BYTES = 64 * 1024 * 1024 +MAX_RPA_INDEX_BYTES = 128 * 1024 * 1024 +MAX_RPA_INDEX_ENTRIES = 250_000 +MAX_RPA_INDEX_SEGMENTS = 1_000_000 + + +class ResourceLimitError(ValueError): + """An input exceeded a deliberate memory or structure limit.""" def safe_path(value): @@ -34,12 +44,23 @@ def safe_path(value): return value -def checked_decompress(data): +def checked_decompress(data, max_output=MAX_DECOMPILED_DATA_BYTES, + error_code='LIMIT_DECOMPILED_DATA'): decoder = zlib.decompressobj() - result = decoder.decompress(data) + result = bytearray() + pending = data + while pending: + remaining = max_output - len(result) + chunk = decoder.decompress(pending, remaining + 1) + result.extend(chunk) + if len(result) > max_output: + raise ResourceLimitError(error_code) + pending = decoder.unconsumed_tail + if not pending: + break if not decoder.eof: raise ValueError('Truncated compressed data') - return result + return bytes(result) class CheckedZlib: @@ -80,15 +101,24 @@ def read_index(tool, source, version): size = source.tell() if not 0 <= offset < size: raise ValueError('Invalid archive index offset') + if size - offset > MAX_COMPRESSED_RPA_INDEX_BYTES: + raise ResourceLimitError('LIMIT_RPA_INDEX_COMPRESSED') source.seek(offset) - index = IndexUnpickler(io.BytesIO(checked_decompress(source.read())), + compressed = source.read(MAX_COMPRESSED_RPA_INDEX_BYTES + 1) + if len(compressed) > MAX_COMPRESSED_RPA_INDEX_BYTES: + raise ResourceLimitError('LIMIT_RPA_INDEX_COMPRESSED') + index = IndexUnpickler(io.BytesIO(checked_decompress( + compressed, MAX_RPA_INDEX_BYTES, 'LIMIT_RPA_INDEX_EXPANDED')), encoding='bytes').load() if not isinstance(index, dict): raise TypeError('Invalid archive index') + if len(index) > MAX_RPA_INDEX_ENTRIES: + raise ResourceLimitError('LIMIT_RPA_INDEX_ENTRIES') normalized = {} # Preserve shared pickle segment lists rather than multiplying their # allocations for every path. Each unique list is validated only once. records_by_id = {} + segment_count = 0 for path, entries in index.items(): path = safe_path(path) if path in normalized or not isinstance(entries, (list, tuple)) or not entries: @@ -98,6 +128,9 @@ def read_index(tool, source, version): continue records = [] for entry in entries: + segment_count += 1 + if segment_count > MAX_RPA_INDEX_SEGMENTS: + raise ResourceLimitError('LIMIT_RPA_INDEX_SEGMENTS') extended_index = getattr(version, 'extended_index', False) if extended_index and isinstance(entry, (list, tuple)) and len(entry) in (4, 5, 6, 7): # This extended layout ignores first/end/end2/dlen2 metadata. Its dlen @@ -142,7 +175,7 @@ def find_offset_and_key(self, source): def archive_index(tool, source, options): try: return read_index(tool, source, tool.detect_version()) - except (MemoryError, OverflowError): + except (MemoryError, OverflowError, ResourceLimitError): raise except Exception: if not options.get('try_harder'): @@ -386,8 +419,25 @@ def write_bytes(path, data): output.writestr(reserve(path), data) result['written'] += 1 - def script(path, data): - text, logs = pyc_decompiler.decompile(data) if path.lower().endswith('.pyc') else decompile(data, options) + def copy_source(path, source): + with output.open(reserve(path), 'w', force_zip64=True) as destination: + while True: + chunk = source.read(CHUNK) + if not chunk: + break + destination.write(chunk) + result['written'] += 1 + + def script(path, data, preserve_input=False): + try: + text, logs = pyc_decompiler.decompile(data) if path.lower().endswith('.pyc') else decompile(data, options) + except ResourceLimitError as error: + if str(error) != 'LIMIT_DECOMPILED_DATA': + raise + if preserve_input: + write_bytes(path, data) + warn(path, 'Декомпиляция пропущена: распакованные данные сценария превышают 256 МиБ. Оригинал сохранён.') + return target = source_name(path) write_bytes(target, text) for log in logs: @@ -403,10 +453,19 @@ def script(path, data): input_paths.add(path) with open(entry['source'], 'rb') as source: if path.lower().endswith(('.rpyc', '.rpymc', '.pyc')) and mode != 'unrpa': + source.seek(0, 2) + input_size = source.tell() + source.seek(0) + if input_size > MAX_DECOMPILE_INPUT_BYTES: + copy_source(path, source) + warn(path, 'Декомпиляция пропущена: файл сценария превышает 128 МиБ. Оригинал сохранён.') + result['succeeded'] += 1 + notify({'type': 'file', 'index': number, 'path': path, 'state': 'done'}) + continue data = source.read() if path.lower().endswith('.pyc'): write_bytes(path, data) - script(path, data) + script(path, data, preserve_input=not path.lower().endswith('.pyc')) elif path.lower().endswith('.rpa') and mode != 'unrpyc': tool = UnRPA(entry['source']) index = archive_index(tool, source, options) @@ -418,13 +477,18 @@ def script(path, data): notify({'type': 'entry', 'index': number, 'path': target, 'current': count + 1, 'total': len(index)}) stream = Segments(source, segments) - compiled = io.BytesIO() if mode == 'combined' and name.lower().endswith(('.rpyc', '.rpymc', '.pyc')) else None + is_compiled = name.lower().endswith(('.rpyc', '.rpymc', '.pyc')) + compiled_size = sum(length for _, length, _ in segments) if is_compiled else 0 + can_decompile = mode == 'combined' and is_compiled and compiled_size <= MAX_DECOMPILE_INPUT_BYTES + compiled = io.BytesIO() if can_decompile else None with output.open(reserve(target), 'w', force_zip64=True) as destination: for chunk in iter(stream.read, b''): destination.write(chunk) if compiled is not None: compiled.write(chunk) result['written'] += 1 + if mode == 'combined' and is_compiled and not can_decompile: + warn(target, 'Декомпиляция пропущена: файл сценария превышает 128 МиБ. Оригинал сохранён.') if compiled is not None: try: generated = source_name(target) diff --git a/templates/resources_list.html b/templates/resources_list.html index 11256a4..9f498c0 100644 --- a/templates/resources_list.html +++ b/templates/resources_list.html @@ -54,8 +54,8 @@ data-variant-count="{{ family.variants|length }}"> {% if primary.thumb %} + data-media-surface data-zoom="{{ family.title or primary.code }}" data-file="{{ primary.name }}.webp" + aria-label="Открыть «{{ family.title or primary.code }}» в полном размере"> {% else %} @@ -66,7 +66,8 @@ @@ -75,6 +76,7 @@ {% if variant.rid != primary.rid %}id="{{ variant.rid }}"{% endif %} data-code="{{ variant.code }}" data-name="{{ variant.name }}" data-distance="{{ variant.distance }}" + data-label="{{ family.title or variant.code }}" {% if variant.raw %}data-raw="{{ variant.raw }}"{% endif %} {% if variant.thumb %}data-thumb="{{ variant.thumb }}"{% endif %} data-file="{{ variant.name }}.webp" @@ -87,7 +89,7 @@
- {{ res.copy_button(primary.code) }} + {% if collection == 'original' %}{{ res.copy_button(primary.code) }}{% endif %} {% if primary.raw %}{{ res.dl_button(primary.raw, primary.name + '.webp') }}{% endif %}
@@ -227,6 +229,42 @@

{% endfor %} + {% elif category_meta.media == 'sprites' and collection == 'community' %} + {% if community_sprite_groups %} + + {% for group in community_sprite_groups %} +
+

{{ group.title }}

+ {% if group.desc %}

{{ group.desc }}

{% endif %} + {% if group.author.name %} +

Автор: + {% if group.author.link %}{{ group.author.name }} + {% else %}{{ group.author.name }}{% endif %} +

+ {% endif %} +
    + {% for family in group.families %}{{ sprite_row(family) }}{% endfor %} +
+
+ {% endfor %} + {% endif %} + {% set plain_sprites = items|rejectattr('sprite_group')|list %} + {% if plain_sprites %} +
+ {% if community_sprite_groups %}

Отдельные изображения

+ {% else %}

Спрайты

{% endif %} +
    + {% for item in plain_sprites %}{{ image_row(item, sprite=true) }}{% endfor %} +
+
+ {% endif %} + {% elif category_meta.media == 'characters' %}
    {% for item in items %} diff --git a/templates/tools_unpack.html b/templates/tools_unpack.html index 5327bf9..711dfb8 100644 --- a/templates/tools_unpack.html +++ b/templates/tools_unpack.html @@ -139,6 +139,9 @@

    Файлы

    + +
    +

    Обработка файлов

    diff --git a/tests/rpa_browser.cjs b/tests/rpa_browser.cjs index 3e6536b..dc30bb1 100644 --- a/tests/rpa_browser.cjs +++ b/tests/rpa_browser.cjs @@ -6,11 +6,26 @@ const path = require('node:path'); const { execFileSync } = require('node:child_process'); const { chromium } = require('playwright'); const root = path.resolve(__dirname, '..'); -const fixtures = path.join(root, 'temp/rpa-tree-browser/game'); +const fixtures = path.join(root, 'temp/rpa-tree-browser-audio/game'); const target = process.env.RPA_TEST_URL || 'http://127.0.0.1:8012/tools/unpack?mode=pack'; +// Five seconds of silent PCM exercises real browser playback without external assets. +const wav = Buffer.alloc(44 + 80000); +wav.write('RIFF'); +wav.writeUInt32LE(wav.length - 8, 4); +wav.write('WAVEfmt ', 8); +wav.writeUInt32LE(16, 16); +wav.writeUInt16LE(1, 20); +wav.writeUInt16LE(1, 22); +wav.writeUInt32LE(8000, 24); +wav.writeUInt32LE(16000, 28); +wav.writeUInt16LE(2, 32); +wav.writeUInt16LE(16, 34); +wav.write('data', 36); +wav.writeUInt32LE(wav.length - 44, 40); const resources = { 'my_mod/images/bg.png': Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aWQAAAABJRU5ErkJggg==', 'base64'), - 'my_mod/audio/тема.ogg': Buffer.from([0, 255, 128, 65]), + 'my_mod/audio/тема.wav': wav, + 'my_mod/audio/финал.wav': wav, 'my_mod/empty.txt': Buffer.alloc(0), 'my_mod/script.rpy': Buffer.from('label my_mod_start:\n return\n'), }; @@ -25,6 +40,15 @@ for (const [name, data] of Object.entries(resources)) { try { const context = await browser.newContext({ viewport: { width: 1440, height: 1000 }, colorScheme: 'light' }); const page = await context.newPage(); + await page.addInitScript(() => { + const BrowserAudio = window.Audio; + window.Audio = class extends BrowserAudio { + constructor(...args) { + super(...args); + window.testAudio = this; + } + }; + }); const errors = [], requests = []; page.on('pageerror', error => errors.push(error.message)); context.on('request', request => requests.push([request.method(), request.url()])); @@ -80,7 +104,7 @@ for (const [name, data] of Object.entries(resources)) { assert.equal(saved.suggestedFilename(), 'my_mod.rpa'); const archive = path.join(root, 'temp/rpa-browser/my_mod.rpa'); await saved.saveAs(archive); - assert.match(await page.locator('#tools-result-description').textContent(), /Файлов в RPA: 4/); + assert.match(await page.locator('#tools-result-description').textContent(), /Файлов в RPA: 5/); assert(await page.locator('#tools-pack-integration').isVisible()); assert.match(await page.locator('#tools-pack-install-archive').textContent(), /my_mod\.rpa$/); assert(await page.locator('#tools-export-dialog').isVisible()); @@ -127,7 +151,7 @@ for (const [name, data] of Object.entries(resources)) { 'for name, records in index.items():', ' content = b"".join(data[start ^ key:(start ^ key) + (length ^ key)] for start, length in records)', ' assert content == (pathlib.Path(sys.argv[2]) / name).read_bytes(), name', - 'assert len(index) == 4', + 'assert len(index) == 5', ].join('\n'), archive, fixtures]); await page.locator('#tools-browser-search').fill('script.rpy'); await page.locator('#tools-browser-list button[data-entry-id]').click(); @@ -149,8 +173,62 @@ for (const [name, data] of Object.entries(resources)) { assert.deepEqual(await page.locator('#tools-browser-list button[data-entry-id]').allTextContents(), verifiedPaths); await page.locator('#tools-mode-unpack').check(); await page.locator('#tools-browser-list button').first().waitFor({ state: 'visible', timeout: 90000 }); - await page.locator('#tools-browser-search').fill('тема'); - assert.match(await page.locator('#tools-browser-list').textContent(), /тема.ogg/); + const tracks = page.locator('#tools-browser-list button[data-entry-id]'); + await page.locator('#tools-browser-search').fill('.wav'); + const trackNames = await tracks.allTextContents(); + assert.equal(trackNames.length, 2); + await tracks.first().click(); + const player = page.locator('.res-nowplaying--visible'); + await player.waitFor({ timeout: 5000 }); + const playing = name => page.waitForFunction(name => !window.testAudio.paused + && window.testAudio.currentTime > 0 + && document.querySelector('.res-nowplaying-name').textContent === name, name); + await playing(trackNames[0]); + assert.equal(await player.locator('.res-volume input').evaluate(el => el.style.getPropertyValue('--range-pct')), '100%'); + assert(!await page.evaluate(() => sessionStorage.getItem('es-doc-player-v2'))); + const repeat = player.locator('.res-nowplaying-repeat'); + const nearEnd = () => page.evaluate(() => { window.testAudio.currentTime = window.testAudio.duration - 0.1; }); + await repeat.click(); + assert.equal(await repeat.getAttribute('aria-label'), 'Повтор трека'); + assert(await page.evaluate(() => window.testAudio.loop)); + const firstSrc = await page.evaluate(() => window.testAudio.src); + await nearEnd(); + await page.waitForFunction(src => window.testAudio.src === src && !window.testAudio.paused + && window.testAudio.currentTime < 1, firstSrc); + await repeat.click(); + assert.equal(await repeat.getAttribute('aria-label'), 'Повтор очереди'); + await nearEnd(); + await playing(trackNames[1]); + await nearEnd(); + await playing(trackNames[0]); + await repeat.click(); + assert.equal(await repeat.getAttribute('aria-label'), 'Повтор выключен'); + await nearEnd(); + await playing(trackNames[1]); + await nearEnd(); + await page.locator('.res-nowplaying--ended').waitFor(); + for (const [width, theme] of [[1440, 'light'], [390, 'dark']]) { + await page.setViewportSize({ width, height: 1000 }); + await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme); + assert(await player.evaluate(bar => [...bar.querySelectorAll('button, input')].every(control => { + const bounds = bar.getBoundingClientRect(), rect = control.getBoundingClientRect(); + return rect.width >= 24 && rect.left >= bounds.left && rect.right <= bounds.right; + }))); + await player.screenshot({ path: path.join(downloadReview, 'audio-player-' + theme + '.png') }); + } + await page.setViewportSize({ width: 1440, height: 1000 }); + await page.evaluate(() => document.documentElement.dataset.theme = 'light'); + await tracks.first().click(); + await playing(trackNames[0]); + await player.getByRole('button', { name: 'Остановить' }).click(); + assert(await tracks.first().evaluate(el => el === document.activeElement)); + await tracks.first().click(); + await playing(trackNames[0]); + await page.locator('#tools-browser-search').fill('.png'); + await tracks.first().click(); + await player.waitFor({ state: 'hidden' }); + assert(await page.evaluate(() => window.testAudio.paused && !window.testAudio.hasAttribute('src'))); + await page.locator('#tools-browser-preview img').waitFor(); const extracted = page.waitForEvent('download', { timeout: 90000 }); await page.locator('#tools-export-start').click(); const zip = await extracted; @@ -175,7 +253,7 @@ for (const [name, data] of Object.entries(resources)) { 'with zipfile.ZipFile(sys.argv[1]) as archive:', ' for name in archive.namelist():', ' assert archive.read(name) == (pathlib.Path(sys.argv[2]) / name).read_bytes(), name', - ' assert len(archive.namelist()) == 4', + ' assert len(archive.namelist()) == 5', ].join('\n'), zipPath, fixtures]); assert.deepEqual(errors, []); @@ -207,7 +285,7 @@ for (const [name, data] of Object.entries(resources)) { const removeImages = page.getByRole('button', { name: 'Убрать папку my_mod/images/ и все вложенные файлы', exact: true }); await removeImages.focus(); await page.keyboard.press('Enter'); - assert.match(await page.locator('#tools-count').textContent(), /3 файла/); + assert.match(await page.locator('#tools-count').textContent(), /4 файла/); assert.equal(await page.locator('#tools-browser-list button').filter({hasText: 'images/'}).count(), 0); assert.equal(await page.locator('#tools-browser-list button').filter({hasText: 'audio/'}).count(), 1); assert(await page.locator('#tools-browser-list .tools-remove-source').nth(1).evaluate(el => el === document.activeElement)); @@ -269,6 +347,6 @@ for (const [name, data] of Object.entries(resources)) { assert(contrasts.every(({ ratio }) => ratio >= 3), JSON.stringify({ name, contrasts })); await page.screenshot({ path: path.join(review, name + '.png'), fullPage: true }); } - console.log('Browser RPA creation, cancellation, extraction, byte comparison, local GET-only processing and responsive checks passed.'); + console.log('Browser RPA creation, extraction, audio playback, repeat, cancellation, byte comparison, local GET-only processing and responsive checks passed.'); } finally { await browser.close(); } })().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/tests/test_community_sprites.py b/tests/test_community_sprites.py new file mode 100644 index 0000000..cba712b --- /dev/null +++ b/tests/test_community_sprites.py @@ -0,0 +1,215 @@ +import io +import json +import os +import shutil +import unittest +from pathlib import Path +from unittest.mock import patch +from uuid import uuid4 + +from httpx import ASGITransport, AsyncClient +from PIL import Image + +from app.app import app +from app.utils.config import CONFIG +from app.utils.lifespan.refresh import _watchers +from app.utils.lifespan.resources_cache import parse_resources + + +class CommunitySpriteTests(unittest.IsolatedAsyncioTestCase): + def setUp(self): + self.assets = Path(__file__).resolve().parents[1] / 'temp' / f'test-sprites-{uuid4().hex}' + self.game = self.assets / 'game' + self.game.mkdir(parents=True) + self.addCleanup(shutil.rmtree, self.assets) + for field, value in ( + ('res_path', self.game), ('docs_path', self.assets / 'docs'), + ('cache_path', self.assets / 'cache'), ('sprite_layers', {}), + ('resources', {}), ('resource_search_items', []), + ): + setting = patch.object(CONFIG, field, value) + setting.start() + self.addCleanup(setting.stop) + if hasattr(CONFIG, 'community_sprite_layers'): + setting = patch.object(CONFIG, 'community_sprite_layers', {}) + setting.start() + self.addCleanup(setting.stop) + + def image(self, relative, color, size=(20, 30)): + path = self.assets / relative + path.parent.mkdir(parents=True, exist_ok=True) + Image.new('RGBA', size, color).save(path) + return path + + def catalog(self, distances=None, author=None): + self.image('game/images/body.png', (255, 0, 0, 255)) + self.image('community/sprites/clothes.png', (0, 255, 0, 128)) + self.image('community/sprites/smile.png', (0, 0, 255, 128)) + data = {'groups': {'Лена в полицейской форме': { + 'author': author or {'name': 'Художник', 'link': 'https://example.com/artist'}, + 'description': 'Спрайт из модификации «Главный Атрибут Пионера»', + 'variations': [{'name': 'Улыбается', 'distances': distances or { + 'far': ['sprites/smile.png'], + 'normal': ['/resource/raw/images/body.png', + '/resource/community/sprites/clothes.png', + 'sprites/smile.png'], + 'close': ['sprites/clothes.png'], + }}], + }}} + (self.assets / 'community-sprites.json').write_text( + json.dumps(data, ensure_ascii=False), encoding='utf-8') + + async def get(self, url): + async with AsyncClient(transport=ASGITransport(app=app), base_url='http://localhost') as client: + return await client.get(url) + + def test_catalog_loads_ordered_distances_and_searchable_metadata(self): + self.catalog() + parse_resources() + items = CONFIG.resources['community']['sprites'] + self.assertEqual(len(items), 1, 'Referenced sprite layers must not be listed separately') + self.assertEqual([v['distance'] for v in items[0]['variants']], ['normal', 'close', 'far']) + self.assertEqual(items[0]['primary']['distance'], 'normal') + self.assertIn('Улыбается close', items[0]['search']) + search = next(r for r in CONFIG.resource_search_items if 'Улыбается' in r['label']) + self.assertIn('Лена в полицейской форме', search['label']) + self.assertIn('Художник', search['keywords']) + self.assertIn('Главный Атрибут Пионера', search['desc']) + + async def test_listing_renders_group_author_and_distance_controls(self): + self.catalog() + parse_resources() + response = await self.get('/resources/community/sprites') + self.assertEqual(response.status_code, 200) + self.assertIn('Лена в полицейской форме', response.text) + self.assertIn('href="https://example.com/artist"', response.text) + self.assertIn('data-distance="close"', response.text) + self.assertIn('data-total="3"', response.text) + self.assertNotIn('class="res-copy res-icon', response.text) + + async def test_composes_layers_in_order_and_serves_thumbnail(self): + self.catalog() + parse_resources() + item = CONFIG.resources['community']['sprites'][0] + response = await self.get(item['raw']) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.headers['content-type'], 'image/webp') + with Image.open(io.BytesIO(response.content)) as image: + self.assertEqual(image.size, (20, 30)) + red, green, blue, alpha = image.convert('RGBA').getpixel((0, 0)) + self.assertLess(abs(red - 63), 8) + self.assertLess(abs(green - 64), 8) + self.assertLess(abs(blue - 128), 8) + self.assertEqual(alpha, 255) + thumb = await self.get(item['thumb']) + self.assertEqual(thumb.status_code, 200) + self.assertEqual(thumb.headers['content-type'], 'image/webp') + + async def test_changed_layer_invalidates_composition_and_thumbnail(self): + self.catalog({'normal': ['sprites/smile.png']}) + parse_resources() + item = CONFIG.resources['community']['sprites'][0] + old = await self.get(item['thumb']) + source = self.image('community/sprites/smile.png', (255, 0, 0, 255)) + newer = source.stat().st_mtime_ns + 2_000_000_000 + os.utime(source, ns=(newer, newer)) + new = await self.get(item['thumb']) + self.assertEqual(new.status_code, 200) + self.assertNotEqual(old.content, new.content) + + def test_rejects_unsafe_missing_and_empty_distances_but_keeps_valid(self): + self.catalog({'normal': ['../game/images/body.png'], + 'close': ['sprites/clothes.png'], 'far': []}) + parse_resources() + custom = [i for i in CONFIG.resources['community']['sprites'] if i.get('variants')] + self.assertEqual(len(custom), 1) + self.assertEqual([v['distance'] for v in custom[0]['variants']], ['close']) + for path in ('/resource/raw/../secret.png', 'C:/secret.png', + '//example.com/image.png', 'https://example.com/image.png', + '/resource/community/%2e%2e/game/images/body.png', 'sprites/missing.png'): + with self.subTest(path=path): + self.catalog({'normal': [path]}) + parse_resources() + self.assertFalse(any(i.get('variants') for i in CONFIG.resources['community']['sprites'])) + + async def test_unsafe_author_link_is_not_rendered(self): + self.catalog(author={'name': '<Художник>', 'link': 'javascript:alert(1)'}) + parse_resources() + response = await self.get('/resources/community/sprites') + self.assertIn('<Художник>', response.text) + self.assertNotIn('javascript:', response.text) + + async def test_malformed_author_url_does_not_break_the_catalog(self): + self.catalog(author={'name': 'Художник', 'link': 'https://[broken'}) + parse_resources() + response = await self.get('/resources/community/sprites') + self.assertEqual(response.status_code, 200) + self.assertIn('Улыбается', response.text) + self.assertNotIn('https://[broken', response.text) + + async def test_changed_layer_order_changes_url_and_retires_old_route(self): + self.catalog({'normal': ['sprites/clothes.png', 'sprites/smile.png']}) + parse_resources() + previous = CONFIG.resources['community']['sprites'][0]['raw'] + self.catalog({'normal': ['sprites/smile.png', 'sprites/clothes.png']}) + parse_resources() + current = CONFIG.resources['community']['sprites'][0]['raw'] + self.assertNotEqual(previous, current) + self.assertEqual((await self.get(previous)).status_code, 404) + self.assertEqual((await self.get(current)).status_code, 200) + + def test_layer_edits_change_public_urls_after_refresh(self): + self.catalog({'normal': ['sprites/smile.png']}) + parse_resources() + previous = CONFIG.resources['community']['sprites'][0]['raw'] + previous_id = CONFIG.resources['community']['sprites'][0]['rid'] + source = self.image('community/sprites/smile.png', (255, 0, 0, 255)) + newer = source.stat().st_mtime_ns + 2_000_000_000 + os.utime(source, ns=(newer, newer)) + parse_resources() + self.assertNotEqual(CONFIG.resources['community']['sprites'][0]['raw'], previous) + self.assertEqual(CONFIG.resources['community']['sprites'][0]['rid'], previous_id) + + def test_sprite_urls_do_not_depend_on_installation_directory(self): + self.catalog() + parse_resources() + previous = CONFIG.resources['community']['sprites'][0]['raw'] + other = self.assets / 'other-installation' + for directory in ('game', 'community'): + shutil.copytree(self.assets / directory, other / directory) + shutil.copy2(self.assets / 'community-sprites.json', other / 'community-sprites.json') + with patch.object(CONFIG, 'res_path', other / 'game'): + parse_resources() + self.assertEqual(CONFIG.resources['community']['sprites'][0]['raw'], previous) + + async def test_different_layer_sizes_fail_without_caching_a_partial_image(self): + self.catalog({'normal': ['sprites/clothes.png', 'sprites/smile.png']}) + self.image('community/sprites/smile.png', (0, 0, 255, 128), size=(10, 15)) + parse_resources() + response = await self.get(CONFIG.resources['community']['sprites'][0]['raw']) + self.assertEqual(response.status_code, 500) + self.assertFalse(list((self.assets / 'cache').rglob('*.webp'))) + + def test_invalid_json_keeps_previous_catalog_and_deletion_clears_it(self): + self.catalog() + parse_resources() + previous = CONFIG.resources['community']['sprites'] + manifest = self.assets / 'community-sprites.json' + manifest.write_text('{broken', encoding='utf-8') + parse_resources() + self.assertEqual(CONFIG.resources['community']['sprites'], previous) + manifest.unlink() + parse_resources() + self.assertFalse(any(i.get('variants') for i in CONFIG.resources['community']['sprites'])) + + def test_resource_watcher_matches_manifest(self): + matcher = next(match for name, match, _ in _watchers() if name == 'resources') + self.assertTrue(matcher((self.assets / 'community-sprites.json').resolve())) + + async def test_unknown_custom_sprite_and_traversal_return_404(self): + self.catalog() + parse_resources() + for url in ('/resource/community-sprite/unknown', + '/resource/thumb/community-sprite/unknown', + '/resource/thumb/community-sprite/..%2Fsecret'): + self.assertEqual((await self.get(url)).status_code, 404) diff --git a/tests/tools_code_browser.cjs b/tests/tools_code_browser.cjs new file mode 100644 index 0000000..461eca7 --- /dev/null +++ b/tests/tools_code_browser.cjs @@ -0,0 +1,91 @@ +/* Start ES Doc on port 8012 and provide Playwright through NODE_PATH. */ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { chromium } = require('playwright'); + +(async () => { + const browser = await chromium.launch({ headless: true, channel: process.env.PLAYWRIGHT_CHANNEL || 'msedge' }); + try { + const page = await browser.newPage(); + const errors = []; + page.on('pageerror', error => errors.push(error.message)); + await page.goto(process.env.TOOLS_TEST_URL || 'http://127.0.0.1:8012/tools/unpack?mode=pack'); + const text = Array.from({ length: 300 }, (_, i) => `# ${i} ${'long line '.repeat(40)}`).join('\n'); + await page.locator('#tools-files').setInputFiles({ + name: 'long-script.rpy', mimeType: 'text/plain', buffer: Buffer.from(text), + }); + await page.locator('#tools-browser-list button[data-entry-id]').click(); + const pre = page.locator('.tools-code-frame pre'); + const toggle = page.locator('.tools-code-expand'); + const settled = () => page.waitForFunction(() => document.querySelector('.tools-code-frame').getAnimations().length === 0); + const controlOffset = () => toggle.evaluate(el => { + const button = el.getBoundingClientRect(); + const frame = el.closest('.tools-code-frame').getBoundingClientRect(); + return { right: frame.right - button.right, top: button.top - frame.top }; + }); + await pre.waitFor({ timeout: 90000 }); + const output = path.resolve(__dirname, '../temp/tools-code-review'); + fs.mkdirSync(output, { recursive: true }); + for (const width of [1440, 390]) { + await page.setViewportSize({ width, height: 900 }); + for (const theme of ['light', 'dark']) { + await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme); + await pre.evaluate(el => { el.scrollTop = 0; el.scrollLeft = 0; }); + assert(await pre.evaluate(el => el.scrollWidth > el.clientWidth && el.scrollHeight > el.clientHeight)); + assert.equal(await pre.locator('.code-scroll').evaluate(el => getComputedStyle(el).overflowX), 'visible'); + await pre.focus(); + await page.keyboard.press('ArrowRight'); + assert(await pre.evaluate(el => el.scrollLeft > 0)); + assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)); + const inlineOffset = await controlOffset(); + await page.locator('.tools-code-frame').evaluate(el => el.scrollIntoView({ block: 'center' })); + await page.screenshot({ path: path.join(output, `${width}-${theme}-inline.png`) }); + await page.getByRole('button', { name: 'На весь экран', exact: true }).click(); + await settled(); + const dialog = page.locator('#tools-code-dialog'); + assert(await dialog.isVisible()); + assert.equal(await toggle.getAttribute('aria-label'), 'Свернуть'); + const expandedOffset = await controlOffset(); + assert(Math.abs(inlineOffset.right - expandedOffset.right) <= 1); + assert(Math.abs(inlineOffset.top - expandedOffset.top) <= 1); + assert.equal(await page.locator('.tools-code-toolbar .code-copy').count(), 1); + assert((await dialog.locator('code').textContent()).trimEnd() === text.trimEnd(), 'Expanded code preserves source'); + assert(await dialog.evaluate(el => { + const rect = el.getBoundingClientRect(); + return rect.x === 0 && rect.y === 0 && Math.abs(rect.width - innerWidth) < 1 + && Math.abs(rect.height - innerHeight) < 1 && el.scrollWidth <= el.clientWidth; + })); + assert(await pre.evaluate(el => el.clientHeight > 600)); + await pre.evaluate(el => { el.scrollTop = 500; el.scrollLeft = 100; }); + await page.screenshot({ path: path.join(output, `${width}-${theme}-expanded.png`) }); + await page.keyboard.press('Escape'); + await dialog.waitFor({ state: 'hidden' }); + assert(await pre.evaluate(el => el.scrollTop === 500 && el.scrollLeft === 100)); + assert(await page.locator('.tools-code-expand').evaluate(el => el === document.activeElement)); + await toggle.click(); + await settled(); + await toggle.click(); + await dialog.waitFor({ state: 'hidden' }); + assert((await page.locator('#tools-browser-preview code').textContent()).trimEnd() === text.trimEnd(), 'Restored code preserves source'); + } + } + // Motion remains reversible during opening; reduced motion avoids scaling. + await toggle.dispatchEvent('click'); + assert(await page.locator('.tools-code-frame').evaluate(el => + el.getAnimations().some(animation => animation.effect.getTiming().duration === 260))); + await toggle.dispatchEvent('click'); + await page.locator('#tools-code-dialog').waitFor({ state: 'hidden' }); + await page.emulateMedia({ reducedMotion: 'reduce' }); + await toggle.click(); + assert(await page.locator('.tools-code-frame').evaluate(el => + el.getAnimations().every(animation => animation.effect.getKeyframes().every(frame => !frame.transform)))); + await settled(); + await page.keyboard.press('Escape'); + await page.locator('#tools-code-dialog').waitFor({ state: 'hidden' }); + assert.deepEqual(errors, []); + console.log('Code preview: scrolling, fullscreen, Escape, focus and restoration passed at desktop/mobile widths in both themes.'); + } finally { + await browser.close(); + } +})().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/tests/tools_ui.test.mjs b/tests/tools_ui.test.mjs index 1a05d65..f98e620 100644 --- a/tests/tools_ui.test.mjs +++ b/tests/tools_ui.test.mjs @@ -67,6 +67,8 @@ function page(search = '', withClipboard = false) { menu.children = [get('tools-pick-files'), get('tools-pick-folder')]; const messages = [], workers = [], revoked = [], blobs = []; const window = new Element(); window.location = { search }; + const played = []; + window.ESDocPlayer = { playLocal: track => played.push(track), stopLocal() {} }; const copied = []; if (withClipboard) { window.navigator = { clipboard: {} }; @@ -102,7 +104,7 @@ function page(search = '', withClipboard = false) { send({ type: 'done', result: total }); }; return { get: name => get('tools-' + name), document, archiveRadio, scriptRadio, - messages, workers, revoked, blobs, window, send, catalog, add, exportDone, result, copied }; + messages, workers, revoked, blobs, window, send, catalog, add, exportDone, result, copied, played }; } const script = { id: '0:script.rpyc', path: 'script.rpyc', source: 0, size: 1 }; @@ -507,8 +509,8 @@ test('PYC accepts uploads and shows Python source preview', async () => { assert.equal(pending.type, 'source-read') ui.send({ type: 'source-file', requestId: pending.requestId, name: 'module.py', buffer: new TextEncoder().encode('answer = 42\n').buffer, warnings: [], html: null }) - assert.equal(ui.get('browser-preview').children[2].download, 'module.py') - assert.match(ui.get('browser-preview').children[1].children[0].children[1].children[0].textContent, /answer = 42/) + assert.equal(ui.get('browser-preview').children[1].download, 'module.py') + assert.match(ui.get('browser-preview').children[0].children[1].children[1].children[0].textContent, /answer = 42/) }) for (const [name, mime] of [['track.OPUS', 'audio/ogg'], ['track.FLAC', 'audio/flac']]) { @@ -521,12 +523,12 @@ for (const [name, mime] of [['track.OPUS', 'audio/ogg'], ['track.FLAC', 'audio/f ui.send({ type: 'source-file', requestId: ui.messages.at(-1).requestId, name, buffer: new Uint8Array([1, 2, 3]).buffer }); assert.equal(ui.blobs.at(-1).type, mime); - const media = ui.get('browser-preview').children[1]; - assert.equal(media.tagName, 'AUDIO'); - assert.equal(media.controls, true); - assert.equal(media.preload, 'metadata'); - assert.match(media.src, /^blob:/); - assert.equal(ui.get('browser-preview').children[2].download, name); + const track = ui.played.at(-1); + const download = ui.get('browser-preview').children[1]; + assert.equal(track.name, name); + assert.match(track.src, /^blob:/); + assert.equal(download.href, track.src); + assert.equal(download.download, name); assert.equal(button.children[0].className, 'tools-ui-icon tools-icon-media'); }); } @@ -558,10 +560,10 @@ test('click requests one source and renders highlighted code with a separate gut const html = 'label start:\n'; ui.send({ type: 'source-file', requestId: read.requestId, name: 'script.rpy', html, buffer: new TextEncoder().encode('label start:\n').buffer }); - const pre = ui.get('browser-preview').children[1].children[0]; + const pre = ui.get('browser-preview').children[0].children[1]; assert.equal(pre.children[0].textContent, '1'); assert.equal(pre.children[1].children[0].innerHTML, html); - assert.equal(ui.get('browser-preview').children[2].download, 'script.rpy'); + assert.equal(ui.get('browser-preview').children[1].download, 'script.rpy'); assert.equal(ui.get('downloads').children.length, 0); }); @@ -571,19 +573,20 @@ test('preview uses the shared code panel and copies source text without the gutt const text = 'label start:\n pass\n'; ui.send({ type: 'source-file', requestId: ui.messages.at(-1).requestId, name: 'script.rpy', buffer: new TextEncoder().encode(text).buffer }); - const frame = ui.get('browser-preview').children[1]; + const frame = ui.get('browser-preview').children[0]; assert.equal(frame.className, 'code-block code-block--numbered tools-code-frame'); - assert.equal(frame.children[1].className, 'code-copy'); - const pre = frame.children[0], scroll = pre.children[1]; + const copy = frame.children[0].children[1].children[0]; + assert.equal(copy.className, 'code-copy'); + const pre = frame.children[1], scroll = pre.children[1]; assert.equal(pre.tabIndex, 0); assert.equal(pre.attributes['aria-label'], 'Код файла'); assert.notEqual(scroll.tabIndex, 0); - scroll.scrollLeft = 0; + pre.scrollLeft = 0; let prevented = false; pre.emit('keydown', { key: 'ArrowRight', preventDefault: () => { prevented = true; } }); - assert.equal(scroll.scrollLeft, 40); + assert.equal(pre.scrollLeft, 40); assert.equal(prevented, true); - frame.children[1].click(); + copy.click(); assert.deepEqual(ui.copied, [text]); }); @@ -636,8 +639,8 @@ test('switching files reuses ready previews and warnings without another worker const requests = ui.messages.length; open(0); assert.equal(ui.messages.length, requests); - assert.equal(ui.get('browser-preview').children[0].children[0].textContent, 'script.rpy'); - assert.equal(ui.get('browser-preview').children[0].children[1].hidden, false); + assert.equal(ui.get('browser-preview').children[0].children[0].children[0].children[0].textContent, 'script.rpy'); + assert.equal(ui.get('browser-preview').children[0].children[0].children[0].children[1].hidden, false); assert.equal(ui.get('cancel').hidden, true); ui.get('no-init-offset').checked = true; ui.get('no-init-offset').emit('change'); assert.equal(ui.messages.length, requests + 1); @@ -821,7 +824,7 @@ test('file warnings use the same indicator next to the filename, with safely ren ui.get('browser-list').children[0].children[0].click(); ui.send({ type: 'source-file', requestId: ui.messages.at(-1).requestId, name: 'script.rpy', buffer: new TextEncoder().encode('label start:').buffer, warnings: [''] }); - const heading = ui.get('browser-preview').children[0]; + const heading = ui.get('browser-preview').children[0].children[0].children[0]; assert.equal(heading.children[0].textContent, 'script.rpy'); const warning = heading.children[1]; assert.equal(warning.open, false); @@ -831,7 +834,7 @@ test('file warnings use the same indicator next to the filename, with safely ren assert.equal(diagnostic.children[2].children[0].textContent, 'Техническое сообщение'); assert.equal(diagnostic.children[2].children[1].textContent, ''); assert.equal(warning.children[1].attributes['aria-label'], 'Причины предупреждений файла'); - assert.equal(ui.get('browser-preview').children[2].download, 'script.rpy'); + assert.equal(ui.get('browser-preview').children[1].download, 'script.rpy'); }); test('legacy warnings show the Russian explanation before the original log in the file preview', async () => { @@ -840,7 +843,7 @@ test('legacy warnings show the Russian explanation before the original log in th const message = "Warning: analysis found signs that this .rpyc file was generated by ren'py\n version 7 or below, while this unrpyc version targets ren'py\n version 8. Decompilation will still be attempted."; ui.send({ type: 'source-file', requestId: ui.messages.at(-1).requestId, name: 'script.rpy', buffer: new TextEncoder().encode('label start:').buffer, warnings: [message] }); - const diagnostic = ui.get('browser-preview').children[0].children[1].children[1].children[0]; + const diagnostic = ui.get('browser-preview').children[0].children[0].children[0].children[1].children[1].children[0]; assert.match(diagnostic.children[1].textContent, /Файл декомпилирован/); assert.match(diagnostic.children[1].textContent, /возможны ошибки и неточности/); assert.equal(diagnostic.children[2].children[1].textContent, message);