diff --git a/AGENTS.md b/AGENTS.md index 43737f9..88179d8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,73 +1,76 @@ -# AGENTS.md — Verbindliche Arbeitsregeln für den Sprite-Viewer +# AGENTS.md — Binding working rules for the Sprite-Viewer -Diese Datei ist verbindlich. Jeder Agent, der in diesem Repository arbeitet, MUSS -diese Regeln vor jeder Aktion gelesen und verstanden haben. +This file is binding. Every agent working in this repository MUST have read +and understood these rules before taking any action. -## 6. Bestätigungspflicht (VOR jeder Operation) +## 1. Language — EVERYTHING IN ENGLISH (non-negotiable) -**Standard-Verfahren für jede Aktion, die etwas verändert (löscht, bewegt, -überschreibt, schreibt, installiert, bereinigt): zunächst dem Menschen eine -konkrete Liste der betroffenen Pfade/Dateien vorlegen, die exakt benannten -Aktionstate zeigen und auf sein ausdrückliches „ja" warten, BEVOR die -Ausführung beginnt. Kein Bestätigen „im selben Atemzug" mit der Ausführung. -Ausnahme nur bei rein lesenden Aktionen, die den Zustand nicht verändern. +All code, comments, identifiers, documentation (including this file, README, +CHANGELOG, docs/), commit messages, issue/PR titles and descriptions, and any +communication with the human are written in English — no other language in any +repository artifact. Existing non-English content (e.g. this file) is +translated to English and stays English. -## 1. Arbeitsbereich (NICHT verhandelbar) +## 2. Confirmation duty (BEFORE every operation) -- Arbeite **AUSSCHLIESSLICH** innerhalb des Projektordners - `sprite-viewer/`. Niemals außerhalb — auch nicht zum „Helfen", „Suchen" oder - „Wiederherstellen". -- Das Durchsuchen, Lesen oder Verändern von Pfaden außerhalb dieses - Projektordners (z. B. `/home/pi/PROG/...`, Papierkorb, Home, History-Ordner - anderer Apps) ist **verboten**, es sei denn, der Mensch erteilt es - **ausdrücklich und mehrmals** für einen **konkret benannten** Pfad. -- Wenn für eine Rettung/Aufräumaktion ein Zugriff außerhalb des Projekts nötig - wäre: **Stopp und frage den Menschen.** Mach ohne dessen Zustimmung GAR nichts. +**Standard procedure for every action that changes something (deletes, moves, +overwrites, writes, installs, cleans up): first present the human a concrete +list of the affected paths/files showing the exactly named action steps, and +wait for their explicit "yes" BEFORE execution begins. No confirming "in the +same breath" as executing. Exception only for purely read-only actions that do +not change state. -## 2. Destruktive Aktionen (Löschen, Bewegen, Umschreiben) +## 3. Working area (non-negotiable) -- **Niemals** Dateien oder Verzeichnisse löschen, ohne dass der Mensch es - **ausdrücklich angeordnet hat** — weder im Projekt noch anderswo. -- **Gitignierte Verzeichnisse sind absolut tabu**, sofern der Mensch es nicht - ausdrücklich sagt. Sie gehören dem Menschen (z. B. temporäre Skripte). - Dazu gehört hier insbesondere: `WORKX/` (siehe `.gitignore`). -- Kein `rm -r`, kein `mv` in fremde Bereiche, kein Umbenennen, das Inhalte - verliert. Bei Unsicherheit: NICHTS tun und fragen. -- Ein irreversibler Fehler (gelöschte, private Dateien) macht nicht - führungsloses Herumwühlen im System nötig — schlimmer noch: Dieses Wühlen - bricht dieselbe Regel erneut. Stoppen und ehrlich kommunizieren. +- Work **EXCLUSIVELY** inside the project folder `sprite-viewer/`. Never + outside — not even to "help", "search" or "restore". +- Searching, reading or modifying paths outside this project folder (trash, + home, history folders of other apps, etc.) is **forbidden**, unless the + human grants it **explicitly and repeatedly** for a **concretely named** + path. +- If a rescue/cleanup action would require access outside the project: **stop + and ask the human.** Do NOTHING without their consent. -## 3. Projektarchitektur (eingehaltene Konventionen) +## 4. Destructive actions (deleting, moving, rewriting) -- **src-Layout (PEP 517)**: Das Paket liegt in `src/spriteviewer/`. - Entwicklungs-Einstieg ist `main.py` (hängt `src/` auf den `sys.path`); - installierter Einstieg ist die Console-Script-Funktion in +- **Never** delete files or directories unless the human has **explicitly + ordered** it — neither in the project nor elsewhere. +- **Gitignored directories are absolutely off-limits**, unless the human says + so explicitly. They belong to the human (e.g. temporary scripts). This + includes in particular here: `WORKX/` (see `.gitignore`). +- No `rm -r`, no `mv` into foreign areas, no renaming that loses content. When + in doubt: do NOTHING and ask. +- An irreversible mistake (deleted, private files) does not justify aimless + rummaging through the system — worse: such rummaging breaks the same rule + again. Stop and communicate honestly. + +## 5. Project architecture (conventions to keep) + +- **src-layout (PEP 517)**: The package lives in `src/spriteviewer/`. + Development entry point is `main.py` (adds `src/` to `sys.path`); the + installed entry point is the console-script function in `src/spriteviewer/app.py:main`. -- **CLI = GNU getopt** (stdlib `getopt.gnu_getopt`), bewusst KEIN argparse: - - Optionen und Sprite dürfen durcheinander stehen (interleave). - - `-S 32`, `-S32`, `--size 32`, `--size=32` sind alle äquivalent. - - `--` beendet die Options-Parsing. - - **Es gibt KEIN `--sprite`/`-s`**: Der Sprite-Dateipfad ist rein - positionell (erster Operand; Default: gebündeltes Sprite). -- **SVG-Assets**: Die einzige Quelle sind die gebündelten Kopien in - `src/spriteviewer/{icons,spriteviewer}.svg` (installiert durch - `install.py`/`sync_assets`). Im Projekt-Root liegen keine doppelten - SVG-Repräsentationen (keine Duplikate anlegen). +- **CLI = GNU getopt** (stdlib `getopt.gnu_getopt`), deliberately NO argparse: + - Options and the sprite may interleave. + - `-S 32`, `-S32`, `--size 32`, `--size=32` are all equivalent. + - `--` ends option parsing. + - **There is NO `--sprite`/`-s`**: The sprite file path is purely positional + (first operand; default: bundled sprite). +- **SVG assets**: The only source is the bundled copies in + `src/spriteviewer/{icons,spriteviewer}.svg` (installed via + `install.py`/`sync_assets`). No duplicate SVG representations in the project + root (do not create duplicates). -## 4. Umgang mit Assets und History +## 6. Handling assets and history -- Keine Asset-Dateien blind aus `build/`-Artefakten, History-Ordnern oder - fremden Kopien „zurücksynchronisieren" — der Quellstand ist - `src/spriteviewer/`. -- Falls je ein WORKX-Verlust eintritt: Nicht selbst im Dateisystem wühlen. - Dem Menschen transparent Bericht erstatten und Optionen (Papierkorb, - VSCode-Local-History, Recovery-Tools) **beschreiben**, aber erst nach - ausdrücklicher Freigabe ausführen. +- Do not blindly "resync" asset files from `build/` artifacts, history folders + or foreign copies — the source of truth is `src/spriteviewer/`. -## 5. Verhalten +## 7. Behaviour -- Nie heimlich, nie ohne Rückfrage, nie mehr als vom Menschen verlangt. -- Immer nur das tun, was der Mensch aktuell anfordert — keine übermotivierte - Eigeninitiative, keine „Aufräumaktionen" ohne Auftrag. -- Fehler zugeben, nicht vertuschen; bei Schäden sofort mitteilen und die - nächste Aktion von der Freigabe des Menschen abhängig machen. +- Never secretly, never without asking back, never more than the human asks + for. +- Always do only what the human currently requests — no overzealous own + initiative, no "cleanup actions" without a commission. +- Admit mistakes, do not cover them up; in case of damage report immediately + and make the next action dependent on the human's approval. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..88156af --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,17 @@ +# Changelog + +## 0.2 — 2026-09-23 + +### Added +- Support for compressed sprite files: `.svgz`/`.svg.gz` (gzip) and `.svg.zip` + (zip containing exactly one `.svg`; multiple `.svg` members raise a clear + error). +- Empty-state notice ("no valid svg file with symbols") when the sprite file + contains no `` fragments — the app still opens normally. + +### Changed +- Icon selection now highlights the whole cell with a small border radius and + a minimum 2 px gap between selected icons; the rendering behaves the same + across themes and operating systems and uses the theme palette colors. +- Development rules (AGENTS.md) are now in English and require everything + (code, documentation, commits, communication) to be written in English. diff --git a/README.md b/README.md index 52e0bb0..6cb29fd 100644 --- a/README.md +++ b/README.md @@ -13,11 +13,12 @@ a responsive tile grid. - Fast QtSvg (SVG Tiny) rendering by default, with optional full **SVG 1.1** via **resvg** (gradients, filters, masks, …) — switchable live from the toolbar and via the `--renderer` flag, so sprites like the Tango icon set - render exactly + render exactly (but slower). - Toolbar dropdown to switch the icon size: 16, 32, 64, 128 or 256 px - Icons are rendered asynchronously in the background, so the UI stays responsive - Right-click → **Copy id** or **Copy SVG** puts the fragment id(s) or the - standalone SVG code on the clipboard (works for single and multi-selection) + standalone SVG code on the clipboard (works for single and multi-selection). + You can select multiple icons with Ctrl + click. - **Open Sprite** button in the status bar loads a different SVG sprite at runtime - Status bar shows the selection / icon count - Cross-platform, installable via a one-line installer or `pip` @@ -132,6 +133,11 @@ Any SVG file passed as an argument is used as the sprite, which also lets you hand it files from your file manager. `python -m spriteviewer` works the same way as `./main.py`. +Compressed sprites are read transparently: gzip-packed files (`.svgz` or +`.svg.gz`) and zip archives containing a single `.svg` (`.svg.zip`) work +exactly like plain `.svg` files. A zip with several `.svg` members is rejected +with a clear error — an icon pack is not a sprite. + ## Project structure ``` diff --git a/src/spriteviewer/_version.py b/src/spriteviewer/_version.py index b7c94ba..5b94d95 100644 --- a/src/spriteviewer/_version.py +++ b/src/spriteviewer/_version.py @@ -1,3 +1,3 @@ """Single source of truth for the package version.""" -__version__ = "0.1" +__version__ = "0.2" diff --git a/src/spriteviewer/icon_store.py b/src/spriteviewer/icon_store.py index c532b73..957e422 100644 --- a/src/spriteviewer/icon_store.py +++ b/src/spriteviewer/icon_store.py @@ -2,7 +2,9 @@ from __future__ import annotations +import gzip import xml.etree.ElementTree as ET +import zipfile from dataclasses import dataclass from pathlib import Path @@ -53,6 +55,30 @@ class Icon: svg: str # self-contained SVG document for this icon +def read_sprite_text(path: str | Path) -> str: + """Read an SVG sprite, transparently decompressing .svgz/.svg.gz/.zip.""" + path = Path(path) + suffix = path.suffix.lower() + if suffix in (".svgz", ".gz"): + with gzip.open(path, "rt", encoding="utf-8") as handle: + return handle.read() + if suffix == ".zip": + with zipfile.ZipFile(path) as archive: + members = [ + name for name in archive.namelist() if name.lower().endswith(".svg") + ] + if not members: + raise ValueError(f"'{path}' contains no .svg file") + if len(members) > 1: + raise ValueError( + f"'{path}' contains {len(members)} .svg files; " + "extract the sprite first" + ) + return archive.read(members[0]).decode("utf-8") + with open(path, encoding="utf-8") as handle: + return handle.read() + + class IconStore: """Loads an SVG sprite file and exposes its icons.""" @@ -64,8 +90,7 @@ def __init__( ): self._renderer = resolve_renderer(renderer) if xml is None: - with open(path, encoding="utf-8") as handle: - xml = handle.read() + xml = read_sprite_text(path) self.icons = self._extract(xml) @property diff --git a/src/spriteviewer/main_window.py b/src/spriteviewer/main_window.py index 14e5b2c..caa6adb 100644 --- a/src/spriteviewer/main_window.py +++ b/src/spriteviewer/main_window.py @@ -6,7 +6,7 @@ from pathlib import Path from PySide6.QtCore import QRect, QSize, Qt, QThread, Signal -from PySide6.QtGui import QIcon, QImage, QPixmap +from PySide6.QtGui import QIcon, QImage, QPainter, QPixmap from PySide6.QtWidgets import ( QApplication, QCheckBox, @@ -20,10 +20,12 @@ QMessageBox, QPushButton, QSizePolicy, + QStackedWidget, QStyle, QStyledItemDelegate, QStyleOptionViewItem, QToolBar, + QVBoxLayout, QWidget, ) @@ -64,13 +66,26 @@ class _CenteredIconDelegate(QStyledItemDelegate): """ def paint(self, painter, option, index): - styled = QStyleOptionViewItem(option) - self.initStyleOption(styled, index) - styled.text = "" - styled.icon = QIcon() - widget = styled.widget - style = widget.style() if widget else QApplication.style() - style.drawControl(QStyle.CE_ItemViewItem, styled, painter, widget) + if option.state & QStyle.State_Selected: + # Selection painted directly so it looks the same on every style + # and platform; only the colour comes from the theme palette. + # Inset by 2 px (gap to neighbours) with a small border radius. + painter.save() + try: + painter.setRenderHint(QPainter.RenderHint.Antialiasing) + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(option.palette.highlight()) + painter.drawRoundedRect(option.rect.adjusted(2, 2, -2, -2), 4.0, 4.0) + finally: + painter.restore() + else: + styled = QStyleOptionViewItem(option) + self.initStyleOption(styled, index) + styled.text = "" + styled.icon = QIcon() + widget = styled.widget + style = widget.style() if widget else QApplication.style() + style.drawControl(QStyle.CE_ItemViewItem, styled, painter, widget) icon = index.data(Qt.DecorationRole) if icon is None: @@ -208,10 +223,24 @@ def _build_icon_grid(self): grid.currentItemChanged.connect(self._update_status) grid.itemSelectionChanged.connect(self._update_status) self._grid = grid - self.setCentralWidget(grid) + self._empty_state = self._build_empty_state() + self._stack = QStackedWidget() + self._stack.addWidget(grid) + self._stack.addWidget(self._empty_state) + self.setCentralWidget(self._stack) self._set_icon_size(self._current_size) self._populate_grid() + def _build_empty_state(self) -> QWidget: + """Centered notice shown when the sprite contains no symbols.""" + page = QWidget() + layout = QVBoxLayout(page) + label = QLabel("no valid svg file with symbols") + label.setAlignment(Qt.AlignCenter) + label.setWordWrap(True) + layout.addWidget(label) + return page + def _populate_grid(self): self._grid.clear() width, height = self._cell_size(self._current_size) @@ -221,6 +250,7 @@ def _populate_grid(self): item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) item.setSizeHint(QSize(width, height)) self._grid.addItem(item) + self._stack.setCurrentIndex(0 if self._icons else 1) def _cell_size(self, size: int) -> tuple[int, int]: """Square cell: icon plus the same small margin on every side.""" @@ -250,7 +280,10 @@ def _open_sprite(self): str(self._sprite_path.parent) if self._sprite_path else str(Path.home()) ) path, _ = QFileDialog.getOpenFileName( - self, "Open Sprite", start_dir, "SVG files (*.svg);;All files (*)" + self, + "Open Sprite", + start_dir, + "SVG files (*.svg *.svgz *.svg.gz *.svg.zip);;All files (*)", ) if not path: return diff --git a/tests/test_icon_store.py b/tests/test_icon_store.py index e63ad8b..4f299a7 100644 --- a/tests/test_icon_store.py +++ b/tests/test_icon_store.py @@ -1,5 +1,8 @@ """Tests for parsing and rendering SVG sprites.""" +import gzip +import zipfile + import pytest from spriteviewer.icon_store import IconStore, has_resvg, resolve_renderer @@ -94,3 +97,60 @@ def test_resolve_renderer_unknown_raises(): def test_explicit_resvg_without_package_raises(): with pytest.raises(RuntimeError): resolve_renderer("resvg") + + +def test_reads_gzip_compressed_sprite(tmp_path): + sprite = tmp_path / "sprite.svg.gz" + sprite.write_bytes(gzip.compress(SPRITE.encode("utf-8"))) + + store = IconStore(sprite) + + assert [icon.id for icon in store.icons] == ["icon-a", "icon-b"] + + +def test_reads_svgz_sprite(tmp_path): + sprite = tmp_path / "sprite.svgz" + sprite.write_bytes(gzip.compress(SPRITE.encode("utf-8"))) + + store = IconStore(sprite) + + assert [icon.id for icon in store.icons] == ["icon-a", "icon-b"] + + +def test_reads_zip_containing_single_svg(tmp_path): + sprite = tmp_path / "sprite.svg.zip" + with zipfile.ZipFile(sprite, "w") as archive: + archive.writestr("sprite.svg", SPRITE) + + store = IconStore(sprite) + + assert [icon.id for icon in store.icons] == ["icon-a", "icon-b"] + + +def test_reads_zip_containing_nested_single_svg(tmp_path): + sprite = tmp_path / "sprite.svg.zip" + with zipfile.ZipFile(sprite, "w") as archive: + archive.writestr("icons/sprite.svg", SPRITE) + + store = IconStore(sprite) + + assert [icon.id for icon in store.icons] == ["icon-a", "icon-b"] + + +def test_zip_without_svg_raises(tmp_path): + sprite = tmp_path / "sprite.svg.zip" + with zipfile.ZipFile(sprite, "w") as archive: + archive.writestr("readme.txt", "no svg here") + + with pytest.raises(ValueError): + IconStore(sprite) + + +def test_zip_with_multiple_svgs_raises(tmp_path): + sprite = tmp_path / "sprite.svg.zip" + with zipfile.ZipFile(sprite, "w") as archive: + archive.writestr("one.svg", SPRITE) + archive.writestr("two.svg", SPRITE) + + with pytest.raises(ValueError): + IconStore(sprite) diff --git a/tests/test_main_window.py b/tests/test_main_window.py index a21bc47..77c4c5a 100644 --- a/tests/test_main_window.py +++ b/tests/test_main_window.py @@ -1,6 +1,8 @@ """Tests for the main window's renderer switch.""" import pytest +from PySide6.QtGui import QColor, QPalette +from PySide6.QtWidgets import QLabel, QStyleFactory from spriteviewer.icon_store import IconStore, has_resvg from spriteviewer.main_window import MainWindow @@ -46,3 +48,114 @@ def test_toggling_checkbox_switches_backend(qapp): assert window._store.renderer == "qtsvg" finally: _close(window) + + +EMPTY_SPRITE = ( + '' + '' + "" +) + + +def test_sprite_without_symbols_shows_empty_state_message(qapp): + window = MainWindow(IconStore(xml=EMPTY_SPRITE)) + try: + assert window._stack.currentIndex() == 1 + label = window._empty_state.findChild(QLabel) + assert label is not None + assert label.text() == "no valid svg file with symbols" + finally: + _close(window) + + +def test_loading_sprite_with_symbols_after_empty_returns_to_grid(qapp): + window = MainWindow(IconStore(xml=EMPTY_SPRITE)) + try: + assert window._stack.currentIndex() == 1 + window.load_sprite(IconStore(xml=SPRITE)) + assert window._stack.currentIndex() == 0 + finally: + _close(window) + + +def test_selected_item_fills_the_whole_cell(qapp): + """Selection covers the whole cell with a 2px gap, on every style.""" + window = MainWindow(IconStore(xml=SPRITE), initial_size=64) + try: + window._grid.setCurrentItem(window._grid.item(0)) + qapp.processEvents() + image = window._grid.grab().toImage() + cell = window._grid.visualItemRect(window._grid.item(0)) + highlight = qapp.palette().highlight().color() + + def is_highlight(color) -> bool: + return ( + abs(color.red() - highlight.red()) <= 8 + and abs(color.green() - highlight.green()) <= 8 + and abs(color.blue() - highlight.blue()) <= 8 + ) + + x = cell.x() + cell.width() // 4 # well inside the rounded corners + # inset gap on top and bottom + assert not is_highlight(image.pixelColor(x, cell.y())) + assert not is_highlight(image.pixelColor(x, cell.y() + 1)) + # the central band is highlighted + matching = sum( + 1 + for y in range(cell.y() + 2, cell.y() + cell.height() - 2) + if is_highlight(image.pixelColor(x, y)) + ) + assert matching >= (cell.height() - 4) * 0.97 + finally: + _close(window) + + +@pytest.mark.parametrize("style_name", ["fusion", "windows"]) +def test_selection_looks_the_same_across_styles_and_palettes(qapp, style_name): + """Selection (rounded, 2px inset) is painted itself and must not depend + on which QStyle or colour scheme the platform provides.""" + old_style = qapp.style().objectName() + old_palette = QPalette(qapp.palette()) + try: + style = QStyleFactory.create(style_name) + if style is None: + pytest.skip(f"style {style_name} unavailable") + qapp.setStyle(style) + + dark = QPalette(old_palette) + dark.setColor(QPalette.ColorRole.Window, QColor(30, 30, 30)) + dark.setColor(QPalette.ColorRole.Base, QColor(20, 20, 20)) + dark.setColor(QPalette.ColorRole.Highlight, QColor(0, 120, 215)) + qapp.setPalette(dark) + + window = MainWindow(IconStore(xml=SPRITE), initial_size=64) + try: + window._grid.setCurrentItem(window._grid.item(0)) + qapp.processEvents() + image = window._grid.grab().toImage() + cell = window._grid.visualItemRect(window._grid.item(0)) + highlight = qapp.palette().highlight().color() + + def is_highlight(color) -> bool: + return ( + abs(color.red() - highlight.red()) <= 8 + and abs(color.green() - highlight.green()) <= 8 + and abs(color.blue() - highlight.blue()) <= 8 + ) + + x = cell.x() + cell.width() // 4 + assert not is_highlight(image.pixelColor(x, cell.y())) + assert not is_highlight(image.pixelColor(x, cell.y() + 1)) + matching = sum( + 1 + for y in range(cell.y() + 2, cell.y() + cell.height() - 2) + if is_highlight(image.pixelColor(x, y)) + ) + assert matching >= (cell.height() - 4) * 0.97 + finally: + _close(window) + finally: + qapp.setPalette(old_palette) + restore = QStyleFactory.create(old_style) + if restore is not None: + qapp.setStyle(restore)