Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
121 changes: 62 additions & 59 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -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.
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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 `<symbol>` 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.
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -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

```
Expand Down
2 changes: 1 addition & 1 deletion src/spriteviewer/_version.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
"""Single source of truth for the package version."""

__version__ = "0.1"
__version__ = "0.2"
29 changes: 27 additions & 2 deletions src/spriteviewer/icon_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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."""

Expand All @@ -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
Expand Down
53 changes: 43 additions & 10 deletions src/spriteviewer/main_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -20,10 +20,12 @@
QMessageBox,
QPushButton,
QSizePolicy,
QStackedWidget,
QStyle,
QStyledItemDelegate,
QStyleOptionViewItem,
QToolBar,
QVBoxLayout,
QWidget,
)

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand All @@ -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."""
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading