diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index a2843ad..6dc39c6 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,13 +1,15 @@ -# Builds the sdist/wheel and publishes graphik to PyPI when a version tag is -# pushed. Publishing uses PyPI Trusted Publishing (OIDC) -- no API token is -# stored in the repo. See RELEASING.md for the one-time PyPI configuration and -# the release procedure. +# Builds the sdist/wheel and publishes graphik to PyPI. Publishing uses PyPI +# Trusted Publishing (OIDC) -- no API token is stored in the repo. +# +# Manual only: graphik is released as git tags that consumers install from the +# tag's source archive (see RELEASING.md), and no PyPI project is set up. The workflow is +# kept so PyPI can be turned on later: do the one-time setup it needs, then +# run it from the Actions tab against a v-tag (the tag check below compares +# the ref name with __version__). name: Publish to PyPI on: - push: - tags: - - "v*.*.*" + workflow_dispatch: # Least privilege by default; the publish job opts into id-token below. permissions: diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index e93aa31..2c5e67a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,6 +1,6 @@ # Runs the test suite on every push and pull request so regressions are # caught before merge, rather than relying solely on manual local validation. -# See RELEASING.md / publish.yml for the separate publish-on-tag workflow. +# See RELEASING.md for releases; publish.yml (manual-only PyPI publish) is separate. name: Test on: @@ -54,3 +54,54 @@ jobs: SDL_VIDEODRIVER: dummy SDL_AUDIODRIVER: dummy run: python -m pytest + + archive-install: + # Consumers install graphik from a release tag's source archive, e.g. + # graphik @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.3.0.zip + # (see RELEASING.md). This job builds the same kind of archive from the + # commit under test -- a zip with one top-level graphik-/ folder, + # as GitHub serves it -- installs it into a fresh venv the way a consumer's + # `pip install -r requirements.txt` would, and draws with it. Unlike an + # import of the package alone, drawing loads graphik.py and pygame, so a + # build that dropped either fails here. An archive install never calls git. + name: Install from a release archive + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "3.13" + + - name: Build a GitHub-style source archive + run: | + VERSION="$(python -c 'import sys; sys.path.insert(0, "src/main/python"); from preponderous.graphik._version import __version__; print(__version__)')" + git archive --format=zip --prefix="graphik-${VERSION}/" -o "$RUNNER_TEMP/graphik.zip" HEAD + echo "VERSION=$VERSION" >> "$GITHUB_ENV" + + - name: Install the archive into a fresh venv + run: | + python -m venv "$RUNNER_TEMP/consumer" + "$RUNNER_TEMP/consumer/bin/python" -m pip install --upgrade pip + "$RUNNER_TEMP/consumer/bin/python" -m pip install "graphik @ file://$RUNNER_TEMP/graphik.zip" + + - name: Import and draw with the installed package + # Run from outside the checkout so only the installed copy is importable. + working-directory: ${{ runner.temp }} + env: + SDL_VIDEODRIVER: dummy + SDL_AUDIODRIVER: dummy + run: | + "$RUNNER_TEMP/consumer/bin/python" - <<'PY' + import os + import pygame + import preponderous.graphik as package + from preponderous.graphik import Graphik + + assert package.__version__ == os.environ["VERSION"], package.__version__ + assert "site-packages" in package.__file__, package.__file__ + surface = pygame.Surface((20, 20)) + Graphik(surface).drawRectangle(2, 2, 10, 10, Graphik.red) + assert tuple(surface.get_at((5, 5)))[:3] == Graphik.red + print("installed graphik", package.__version__, "draws OK from", package.__file__) + PY diff --git a/README.md b/README.md index 87fab0e..4d1a0f0 100644 --- a/README.md +++ b/README.md @@ -3,17 +3,30 @@ This library assists developers with graphics programming. +![Rectangles, centred text, a button and an image drawn with graphik](docs/images/hero.png) + +*Every draw method, rendered by graphik itself (`scripts/make_readme_images.py`).* + ## Installation -`graphik` has not been published to PyPI yet (see [RELEASING.md](RELEASING.md) -for the release process), so `pip install graphik` will not resolve until the -first release is published. Until then, install directly from this repository: +graphik is released as git tags, not on PyPI. Install a release from its tag's +archive (no `git` needed): ```bash -pip install git+https://github.com/Stephenson-Software/graphik.git -``` -Once a release is published, it will be installable with: -```bash -pip install graphik +pip install "graphik @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.3.0.zip" ``` +In a `requirements.txt`, use the same line without the quotes. See +[RELEASING.md](RELEASING.md) for how releases are cut. + +## Dependents +These games use graphik. When a release goes out, each one gets a pull request +that bumps the tag in its `requirements.txt`: + +| Game | Repository | +|---|---| +| Roam | [Preponderous-Software/roam](https://github.com/Preponderous-Software/roam) | +| Ophidian | [Preponderous-Software/ophidian](https://github.com/Preponderous-Software/ophidian) | +| Apex | [Preponderous-Software/apex](https://github.com/Preponderous-Software/apex) | +| Rock Paper Scissors 2D | [Stephenson-Software/Rock-Paper-Scissors-2D](https://github.com/Stephenson-Software/Rock-Paper-Scissors-2D) | +| Tic Tak Toe | [Stephenson-Software/Tic-Tak-Toe](https://github.com/Stephenson-Software/Tic-Tak-Toe) | ## Usage ```python @@ -30,12 +43,14 @@ while running: if event.type == pygame.QUIT: running = False + graphik.beginFrame() # optional: buttons fire once per click instead of while held gameDisplay.fill(Graphik.black) graphik.drawRectangle(100, 100, 200, 50, Graphik.blue) graphik.drawText("Hello, world!", 200, 125, 24, Graphik.white) graphik.drawButton(100, 200, 200, 50, Graphik.green, Graphik.black, 24, "Click me", lambda: print("clicked")) graphik.drawImage("path/to/image.png", 100, 300, 200, 200) # replace with a real image file pygame.display.update() + graphik.endFrame() pygame.quit() ``` @@ -48,7 +63,13 @@ Public `Graphik` methods: - `getVersion()` — returns the installed graphik version string. - `drawRectangle(xpos, ypos, width, height, color)` — `xpos`/`ypos` are the rectangle's top-left corner. - `drawText(text, xpos, ypos, size, color)` — `xpos`/`ypos` are the **center** of the rendered text, not its top-left corner. This differs from `drawRectangle`, `drawButton` and `drawImage`, which all position their top-left corner at the given coordinates. Glyph edges are antialiased, blending with whatever is already on the surface. The text is always rendered as a single line — a `"\n"` is not a line break, so multi-line text needs one call per line — and a null character (`"\0"`) raises `ValueError` before anything is painted. -- `drawButton(xpos, ypos, width, height, colorBox, colorText, sizeText, text, function)` — draws a rectangle and centered text, and calls `function()` on every call where the mouse is held inside the button with button 1 down (there is no click-edge detection, so a held-down mouse fires `function()` once per call, not once per click). Callers wanting once-per-click semantics must debounce on their side. The clickable region is exactly the drawn box — `xpos` through `xpos + width - 1`, and `ypos` through `ypos + height - 1` — so buttons laid out edge to edge share no clickable coordinate. The hit test uses `pygame.mouse.get_pos()`, which is in window coordinates, so this only holds when the `Graphik` is bound to the display itself (or another surface whose top-left sits at the window's origin): bound to a subsurface or an off-screen surface blitted elsewhere, the box is painted at that surface's position but stays clickable at `xpos`/`ypos` relative to the window. The label is not clipped to the box: one too large for it overflows past the box edges, and that overflow is painted but not clickable. Reading the mouse needs the video system, so unlike `drawRectangle` and `drawText` it raises `pygame.error` (after painting) when neither `pygame.init()` nor `pygame.display.init()` has been called, even for an off-screen surface; no display mode is needed. +- `beginFrame()` — call once at the top of each frame to make `drawButton` fire once per click instead of while held. Calling it again in the same frame does nothing, so nested screens can each call it. A press that is already held when the first `beginFrame()` runs, or that slides onto a button while held, doesn't count, and each press fires at most one button. +- `endFrame()` — call once at the end of each frame started with `beginFrame()`. A frame that misses it (an exception, an early return) doesn't leave clicks stuck: the next `beginFrame()` notices the mouse button changed and takes a new snapshot. +- `drawButton(xpos, ypos, width, height, colorBox, colorText, sizeText, text, function)` — draws a rectangle and centered text, and calls `function()` when the button is clicked. By default it fires on every call where the mouse is held inside the button with button 1 down (once per call, not once per click), as earlier versions did. After the first `beginFrame()` call on the instance, it fires once per click instead: only in the frame where button 1 goes down inside the button. While the mouse is over the box, the box is drawn in a lifted color (light colors darken by 25, dark ones lighten by 35, per channel, clamped; the label color is unchanged), so it reads as clickable. The clickable region is exactly the drawn box — `xpos` through `xpos + width - 1`, and `ypos` through `ypos + height - 1` — so buttons laid out edge to edge share no clickable coordinate. The hit test uses `pygame.mouse.get_pos()`, which is in window coordinates, so this only holds when the `Graphik` is bound to the display itself (or another surface whose top-left sits at the window's origin): bound to a subsurface or an off-screen surface blitted elsewhere, the box is painted at that surface's position but stays clickable at `xpos`/`ypos` relative to the window. The label is not clipped to the box: one too large for it overflows past the box edges, and that overflow is painted but not clickable. Reading the mouse needs the video system, so unlike `drawRectangle` and `drawText` it raises `pygame.error` (after painting) when neither `pygame.init()` nor `pygame.display.init()` has been called, even for an off-screen surface; no display mode is needed. + + ![Buttons with the mouse away and over them](docs/images/hover.png) + + *The hover lift, rendered by `scripts/make_readme_images.py`.* - `drawImage(filePath, xpos, ypos, width, height)` — caches the loaded and scaled surface by `filePath`, so an image edited on disk mid-run will not be picked up until the process restarts. `filePath` may be a `str` or a `pathlib.Path`, and is used as the key exactly as given: two spellings of one file (relative and absolute, or a `str` and a `Path`) are cached, and loaded, separately. Only the most recently requested size is kept per path, so drawing the same file at two alternating sizes rescales it on every call. Unlike the other draw methods, it raises `pygame.error` unless a display mode has been set with `pygame.display.set_mode`, even when the `Graphik` is bound to an off-screen surface. Only the first load of a path needs one: a path already in the cache keeps drawing to an off-screen surface with no display mode set. Positions passed to the draw methods need not lie on the surface: anything drawn across its edge (including at negative coordinates) is clipped to it, with the part that falls off simply not painted — nothing raises, and nothing is shifted to fit. @@ -75,10 +96,13 @@ source .venv/bin/activate pip install -e ".[test]" pytest ``` -The suite is headless: `src/test/python/conftest.py` sets `SDL_VIDEODRIVER`/`SDL_AUDIODRIVER` to `dummy` before pygame touches a display, so no window is created and the tests run on a machine with no display attached. `pytest` alone works from the repo root because `[tool.pytest.ini_options]` in `pyproject.toml` points `testpaths` at `src/test/python` and `pythonpath` at `src/main/python`. `.github/workflows/test.yml` runs the same `pip install -e ".[test]"` + `pytest` sequence — preceded by a compile check and an import smoke test, across the supported Python versions — on every pull request and on every push to `main`. A push to a branch with no open pull request is not covered, so run `pytest` locally before opening one. +The suite is headless: `src/test/python/conftest.py` sets `SDL_VIDEODRIVER`/`SDL_AUDIODRIVER` to `dummy` before pygame touches a display, so no window is created and the tests run on a machine with no display attached. `pytest` alone works from the repo root because `[tool.pytest.ini_options]` in `pyproject.toml` points `testpaths` at `src/test/python` and `pythonpath` at `src/main/python`. `.github/workflows/test.yml` runs the same `pip install -e ".[test]"` + `pytest` sequence — preceded by a compile check and an import smoke test, across the supported Python versions — on every pull request and on every push to `main`. A second job, *Install from a release archive*, packs the commit the way GitHub serves a tag's archive, installs it into a fresh venv as a consumer would, and draws with it. A push to a branch with no open pull request is not covered, so run `pytest` locally before opening one. + +The README images are generated, not hand-made. After changing how something draws, regenerate them with +`SDL_VIDEODRIVER=dummy python scripts/make_readme_images.py` and commit the updated `docs/images/*.png`. ## Projects -[Projects that utilize this library](https://github.com/Stephenson-Software/graphik/wiki/Projects) +The games that use graphik are listed under [Dependents](#dependents) above. ## 📄 License diff --git a/RELEASING.md b/RELEASING.md index 4f84414..1c0fe82 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -1,77 +1,61 @@ # Releasing graphik -graphik is published to [PyPI](https://pypi.org/) via **Trusted Publishing** -(OIDC) — no API token is stored in this repository. Publishing is automated by -[`.github/workflows/publish.yml`](.github/workflows/publish.yml), which runs -when a version tag (`vX.Y.Z`) is pushed. +graphik is released as **git tags**. It isn't published to PyPI. Consumers +install a release from the tag's source archive on GitHub: -## One-time setup (maintainer) - -These steps are prerequisites for the workflow to succeed and are done outside -this repository: +``` +graphik @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.3.0.zip +``` -1. **Claim the project name on PyPI.** Register `graphik` (the - [`pyproject.toml`](pyproject.toml) `name`). `preponderous-graphik` is the - namespaced fallback if the name is unavailable. -2. **Configure a Trusted Publisher** on the PyPI project pointing at this repo: - - Owner: `Stephenson-Software` - - Repository: `graphik` - - Workflow filename: `publish.yml` - - Environment name: `pypi` -3. **Create a GitHub environment** named `pypi` (Settings → Environments). An - optional required-reviewer rule can be added there to gate each release. +pip downloads the archive and builds the wheel locally with setuptools, using +[`pyproject.toml`](pyproject.toml). This needs access to GitHub but not `git`, +which matters for players installing a game from source on Windows. (The +`git+https://...@v0.3.0` form also works where `git` is installed.) ## Cutting a release -1. Bump the single version source — +1. Bump the single version source, [`src/main/python/preponderous/graphik/_version.py`](src/main/python/preponderous/graphik/_version.py) - (`__version__`). Every other version reference is derived from it. -2. Commit the bump and merge it to `main`. -3. Tag the release commit and push the tag: + (`__version__`). Every other version reference is derived from it. Use three + dot-separated parts (`0.3.0`), with no `.dev` suffix for a release. +2. Merge the bump to `main`, with green CI. The *Install from a release + archive* job in `test.yml` has already installed and drawn with an archive + built the same way as the tag's. +3. Tag the merge commit as `v` + `__version__`, push the tag, and create a + GitHub release for it: ````bash - git tag v0.2.0 - git push origin v0.2.0 + git tag -a v0.3.0 -m "graphik 0.3.0" + git push origin v0.3.0 + gh release create v0.3.0 --verify-tag --notes "" ```` -4. The `Publish to PyPI` workflow then: - - verifies the tag matches `__version__` (a mismatch fails the build), - - builds the sdist and wheel, - - smoke-tests the built wheel: installs it, runs `import preponderous.graphik`, - and checks `__version__` against the tag. `Graphik` itself is imported - lazily on first access, so this step never loads `graphik.py` or - `pygame` — a wheel with a missing or broken `graphik.py`, or without a - working `pygame` dependency, would still pass it - (tracked in - [#46](https://github.com/Stephenson-Software/graphik/issues/46)), - - publishes to PyPI via Trusted Publishing. +4. Check that the tag installs and imports in a clean environment: -The tag must equal `v` + `__version__` (e.g. `__version__ = "0.2.0"` → tag -`v0.2.0`), and `__version__` must have at least three dot-separated parts, -because the trigger in `publish.yml` is the glob `v*.*.*`, which needs two dots -after the `v`. A tag that matches the trigger but whose version does not match -`__version__` fails the build before anything is published. A tag that does -not match the trigger fails silently instead: the workflow never runs and -nothing reports the missed release. That covers a tag **without** the `v` -prefix, and also a `v`-prefixed tag with fewer than three parts such as -`v1.0` — even when it equals `v` + `__version__`. (The `v0.1` tag on this -repository is of that shape, and would not trigger the workflow either.) The -`0.2.0` and `0.3.0.dev20260808` tags were pushed without the prefix, so the -publish workflow has never run (tracked in -[#34](https://github.com/Stephenson-Software/graphik/issues/34)). + ````bash + python -m venv /tmp/g && /tmp/g/bin/pip install "graphik @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.3.0.zip" + SDL_VIDEODRIVER=dummy /tmp/g/bin/python -c "from preponderous.graphik import Graphik, __version__; print(__version__)" + ```` -## Installing (after the first publish) +5. Open a pull request in each repository in the README's + [Dependents](README.md#dependents) list that bumps the tag in its + `requirements.txt`. -Once the package is live on PyPI, consumers can replace their vendored copies -with a versioned dependency: +A released tag must never be moved or deleted: consumers' installs resolve it +by name, so moving it would change what they install without any change on +their side. -````bash -pip install graphik -```` +## Earlier tags -```python -from preponderous.graphik import Graphik -``` +`v0.1`, `0.2.0` and `0.3.0.dev20260808` were pushed before this process. The +last two have no `v` prefix. `v0.3.0` is the first release under it. + +## PyPI (not in use) -Migrating the existing consumers (Roam, Apex, Ophidian, Patchwork, Tic-Tak-Toe) -off their vendored copies is tracked as follow-up work in the consumer repos. +[`.github/workflows/publish.yml`](.github/workflows/publish.yml) can build and +publish to PyPI with Trusted Publishing, but it runs only when started by hand +(`workflow_dispatch`). No PyPI project is set up. To turn it on: claim the +`graphik` name on PyPI (`preponderous-graphik` as a fallback), add a Trusted +Publisher for owner `Stephenson-Software`, repository `graphik`, workflow +`publish.yml`, environment `pypi`, create the `pypi` environment in this +repository's settings, then run the workflow against a `v` tag. diff --git a/docs/images/hero.png b/docs/images/hero.png new file mode 100644 index 0000000..8f16289 Binary files /dev/null and b/docs/images/hero.png differ diff --git a/docs/images/hover.png b/docs/images/hover.png new file mode 100644 index 0000000..1e54c26 Binary files /dev/null and b/docs/images/hover.png differ diff --git a/pyproject.toml b/pyproject.toml index 42224b0..a65834e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,5 +1,5 @@ [build-system] -requires = ["setuptools>=61.0"] +requires = ["setuptools>=77.0"] build-backend = "setuptools.build_meta" [project] @@ -8,11 +8,11 @@ dynamic = ["version"] description = "Simple helper methods for graphics programming with pygame." readme = "README.md" requires-python = ">=3.9" -license = { text = "MIT" } +license = "MIT" +license-files = ["LICENSE"] authors = [{ name = "Daniel McCoy Stephenson" }] dependencies = ["pygame"] classifiers = [ - "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Topic :: Multimedia :: Graphics", ] diff --git a/scripts/make_readme_images.py b/scripts/make_readme_images.py new file mode 100644 index 0000000..a4eaca4 --- /dev/null +++ b/scripts/make_readme_images.py @@ -0,0 +1,115 @@ +"""Render the README images with graphik itself. + +Run from the repository root: + + SDL_VIDEODRIVER=dummy python scripts/make_readme_images.py + +Writes docs/images/hero.png (a sample of every draw method) and +docs/images/hover.png (buttons with the mouse away and over them). Uses the +graphik in src/main/python, not an installed copy, so the images always show +this checkout. No window is opened. +""" + +import os +import sys +import tempfile + +os.environ.setdefault("SDL_VIDEODRIVER", "dummy") +os.environ.setdefault("SDL_AUDIODRIVER", "dummy") + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "src", "main", "python")) + +import pygame # noqa: E402 + +from preponderous.graphik import Graphik # noqa: E402 + +OUT = os.path.join(ROOT, "docs", "images") +BACKGROUND = (245, 244, 240) +INK = (30, 30, 30) +MUTED = (110, 110, 110) + + +def _mouseAt(position): + """Point drawButton's hit test (and hover) at ``position``.""" + pygame.mouse.get_pos = lambda: position + pygame.mouse.get_pressed = lambda num_buttons=3: (0, 0, 0) + + +def _sampleImage(path): + """Write a small gradient tile for drawImage to load.""" + tile = pygame.Surface((32, 32)) + for x in range(32): + for y in range(32): + tile.set_at((x, y), (40 + x * 6, 90 + y * 4, 200 - x * 3)) + pygame.image.save(tile, path) + + +def makeHero(path): + width, height = 760, 260 + display = pygame.display.set_mode((width, height)) + graphik = Graphik(display) + display.fill(BACKGROUND) + + graphik.drawText("graphik", width // 2, 34, 34, INK) + graphik.drawText("drawRectangle, drawText, drawButton and drawImage on a pygame surface", + width // 2, 70, 16, MUTED) + + graphik.drawRectangle(40, 110, 120, 80, Graphik.red) + graphik.drawRectangle(80, 140, 120, 80, Graphik.blue) + graphik.drawText("drawRectangle", 120, 240, 15, MUTED) + + graphik.drawText("Hello, world!", 330, 150, 26, INK) + graphik.drawText("drawText (centred)", 330, 240, 15, MUTED) + + _mouseAt((-100, -100)) + graphik.drawButton(450, 120, 130, 56, Graphik.green, Graphik.black, 22, "Play", lambda: None) + graphik.drawText("drawButton", 515, 240, 15, MUTED) + + with tempfile.TemporaryDirectory() as tmp: + tilePath = os.path.join(tmp, "tile.png") + _sampleImage(tilePath) + graphik.drawImage(tilePath, 620, 110, 100, 100) + graphik.drawText("drawImage", 670, 240, 15, MUTED) + + pygame.image.save(display, path) + + +def makeHover(path): + width, height = 760, 300 + display = pygame.display.set_mode((width, height)) + graphik = Graphik(display) + display.fill(BACKGROUND) + + graphik.drawText("Button hover (on by default)", width // 2, 30, 24, INK) + buttons = [ + ("Dark box", (40, 60, 140), Graphik.white), + ("Light box", (225, 225, 225), INK), + ("Graphik.green", Graphik.green, Graphik.black), + ] + for i, (name, box, text) in enumerate(buttons): + x = 40 + i * 240 + graphik.drawText(name, x + 90, 72, 17, MUTED) + _mouseAt((-100, -100)) + graphik.drawButton(x, 92, 180, 60, box, text, 22, "Play", lambda: None) + graphik.drawText("mouse away", x + 90, 166, 14, MUTED) + _mouseAt((x + 20, 212)) + graphik.drawButton(x, 192, 180, 60, box, text, 22, "Play", lambda: None) + graphik.drawText("mouse over", x + 90, 266, 14, MUTED) + + pygame.image.save(display, path) + + +def main(): + os.makedirs(OUT, exist_ok=True) + pygame.init() + try: + makeHero(os.path.join(OUT, "hero.png")) + makeHover(os.path.join(OUT, "hover.png")) + finally: + pygame.quit() + print("wrote docs/images/hero.png and docs/images/hover.png") + + +if __name__ == "__main__": + main() diff --git a/src/main/python/preponderous/graphik/_version.py b/src/main/python/preponderous/graphik/_version.py index 58f4d2f..493f741 100644 --- a/src/main/python/preponderous/graphik/_version.py +++ b/src/main/python/preponderous/graphik/_version.py @@ -1 +1 @@ -__version__ = "0.3.0.dev20260808" +__version__ = "0.3.0" diff --git a/src/main/python/preponderous/graphik/graphik.py b/src/main/python/preponderous/graphik/graphik.py index 53f03bf..b4ce169 100644 --- a/src/main/python/preponderous/graphik/graphik.py +++ b/src/main/python/preponderous/graphik/graphik.py @@ -78,6 +78,73 @@ def __init__(self, gameDisplay=None): # doesn't need the font cache's session-invalidation logic. self._images = {} self._scaledImages = {} + # Press-only clicks (see beginFrame). Until beginFrame is first + # called, drawButton keeps the original repeat-fire behaviour. + self._frameMode = False + self._frameStarted = False + self._mouseDownPrev = False + self._mouseDownCurrent = False + # True once the current press has fired a callback; cleared when a + # snapshot sees button 1 up. Keeps one press from firing twice. + self._pressSpent = False + + def beginFrame(self): + """Start a frame: snapshot mouse button 1 for press-only clicks. + + Call once at the top of each frame, before any drawButton, and pair + it with endFrame at the end of the frame. From the first call on, + drawButton calls its ``function`` once per click: in the frame where + button 1 goes down while the mouse is over the box. A press that is + already held when the first beginFrame runs, or that slides onto a + button while held, does not count. Like any once-per-frame poll, a + release and a new press that both happen between two frames are not + seen. + + Calling beginFrame again before endFrame, with the mouse button in + the same state, does nothing, so nested code may call it too. If the + button's state has changed since the last snapshot, the call takes a + new snapshot, so a frame that missed its endFrame (an exception, an + early return) does not leave clicks stuck. Each press fires at most + one callback, so a press is never handed to a second button or to a + nested screen's loop that runs inside the first callback. + + An instance that never calls beginFrame keeps the original behaviour, + so existing callers are unaffected. + """ + down = pygame.mouse.get_pressed()[0] == 1 + if not self._frameMode: + # Entering press-only mode: a press already held now is not new. + self._mouseDownCurrent = down + self._pressSpent = down + self._frameMode = True + if not self._frameStarted or down != self._mouseDownCurrent: + self._mouseDownPrev = self._mouseDownCurrent + self._mouseDownCurrent = down + if not down: + self._pressSpent = False + self._frameStarted = True + + def endFrame(self): + """End a frame started with beginFrame, so the next one snapshots again.""" + self._frameStarted = False + + @staticmethod + def _hoverColor(color): + """Return ``color`` lifted for hover: light colors darken, dark ones lighten. + + Light means an average r/g/b of 128 or more; those darken by 25. The + rest lighten by 35. Each channel is clamped to 0-255 and any alpha is + kept. Tuples and lists come back as a tuple of the same length; a + name, hex string or pygame.Color comes back as a pygame.Color. An int + is read as 0xRRGGBBAA here, so drawButton converts a surface-mapped + int to r/g/b before calling this. + """ + c = pygame.Color(color) + shift = -25 if (c.r + c.g + c.b) / 3 >= 128 else 35 + r, g, b = (max(0, min(255, v + shift)) for v in (c.r, c.g, c.b)) + if isinstance(color, (tuple, list)): + return (r, g, b, c.a) if len(color) == 4 else (r, g, b) + return pygame.Color(r, g, b, c.a) def getGameDisplay(self): """Return the pygame surface this instance draws to.""" @@ -179,12 +246,21 @@ def drawText(self, text, xpos, ypos, size, color): self.gameDisplay.blit(textSurface, textRectangle) def drawButton(self, xpos, ypos, width, height, colorBox, colorText, sizeText, text, function): - """Draw a labelled box and call ``function`` while it is being clicked. - - ``function()`` is called on every invocation where the mouse sits - inside the box with button 1 held down -- once per call, not once per - click. A caller wanting once-per-click semantics must debounce on its - own side; see the implementation note below for why. + """Draw a labelled box and call ``function`` when it is clicked. + + By default, ``function()`` is called on every invocation where the + mouse sits inside the box with button 1 held down -- once per call, + not once per click. After the first beginFrame() call on this + instance, it is called once per click instead: only in the frame + where button 1 goes down while the mouse is inside the box. See the + implementation note below for why the default is kept. + + While the mouse is over the box, the box is drawn in a lifted color + (light colors darken, dark ones lighten; see _hoverColor), so it + reads as clickable. The label color is unchanged. "Over the box" uses + the same window coordinates as the hit test (see below), so on an + offset subsurface the hover shows where the box is clickable, not + where it is painted. The clickable region is exactly the region the box is drawn over: ``xpos`` through ``xpos + width - 1`` horizontally, and ``ypos`` @@ -230,27 +306,55 @@ def drawButton(self, xpos, ypos, width, height, colorBox, colorText, sizeText, t and the overflow is painted but not clickable. function: Zero-argument callable invoked as described above. """ - # Polls the current mouse state rather than tracking press/release - # edges, so function() fires on every call where the mouse is held - # inside the button with button 1 down -- once per call, not once - # per click. Deliberately left this way: the vendored copies in - # Roam/Apex/Ophidian/Patchwork/Tic-Tak-Toe are written against this - # repeat-fire behavior. Callers wanting once-per-click semantics - # must debounce on their side. - self.drawRectangle(xpos, ypos, width, height, colorBox) - self.drawText(text, xpos + (width//2), ypos + (height//2), sizeText, colorText) - - # if clicked then do function - mouse = pygame.mouse.get_pos() + # Without beginFrame, this polls the current mouse state rather than + # tracking press/release edges, so function() fires on every call + # where the mouse is held inside the button with button 1 down. That + # default is deliberate: the vendored copies in Roam/Apex/Ophidian/ + # Patchwork/Tic-Tak-Toe were written against this repeat-fire + # behavior. Press-only clicks (ported from Roam's copy) are opt-in + # through beginFrame. + # + # The mouse is read before painting so the box can show hover, but a + # failure to read it (video system not initialised) is raised only + # after the box and label are painted, as before. + try: + mouse = pygame.mouse.get_pos() + mouseError = None + except pygame.error as error: + mouse, mouseError = None, error # Half-open on both axes, matching the range pygame.draw.rect fills, so # the clickable region is exactly the drawn one. A strict `> xpos` here # would leave the painted left and top edge columns unclickable, and a # closed `<= xpos + width` would let edge-to-edge buttons both claim # their shared boundary. - if (xpos <= mouse[0] < xpos + width and ypos <= mouse[1] < ypos + height): - click = pygame.mouse.get_pressed() - if click[0] == 1: + hovering = mouse is not None and ( + xpos <= mouse[0] < xpos + width and ypos <= mouse[1] < ypos + height) + + if hovering: + # pygame.draw.rect reads an int as a pixel already mapped to the + # surface, while pygame.Color reads it as 0xRRGGBBAA, so map it + # back to r/g/b first or the lift would change its hue. + baseColor = colorBox + if isinstance(colorBox, int) and not isinstance(colorBox, bool): + baseColor = self.gameDisplay.unmap_rgb(colorBox) + boxColor = self._hoverColor(baseColor) + else: + boxColor = colorBox + self.drawRectangle(xpos, ypos, width, height, boxColor) + self.drawText(text, xpos + (width//2), ypos + (height//2), sizeText, colorText) + if mouseError is not None: + raise mouseError + + if not hovering: + return + if self._frameMode: + if self._mouseDownCurrent and not self._mouseDownPrev and not self._pressSpent: + # Spend the press before calling out, so a nested loop run by + # the callback, or a later drawButton, can't fire it again. + self._pressSpent = True function() + elif pygame.mouse.get_pressed()[0] == 1: + function() def drawImage(self, filePath, xpos, ypos, width, height): """Draw an image file, scaled to the given size. diff --git a/src/test/python/preponderous/graphik/test_graphik.py b/src/test/python/preponderous/graphik/test_graphik.py index 7a2360d..d47b7ff 100644 --- a/src/test/python/preponderous/graphik/test_graphik.py +++ b/src/test/python/preponderous/graphik/test_graphik.py @@ -9,6 +9,11 @@ import preponderous.graphik as graphik_pkg from preponderous.graphik import Graphik +# drawButton's hover colors for the boxes these tests draw. Both are dark +# (average r/g/b under 128), so each channel lightens by 35, clamped at 255. +BLUE_HOVER = (35, 35, 235) # Graphik.blue (0, 0, 200) +GREEN_HOVER = (35, 235, 35) # Graphik.green (0, 200, 0) + _SRC_MAIN = os.path.normpath( os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "..", "main", "python") ) @@ -1215,7 +1220,7 @@ def _draw_button_at(graphik, imagePath, xpos, ypos): pytest.param(15, 15, id="past_bottom_right"), ], ) -def test_draw_methods_clip_a_shape_that_crosses_the_surface_edge(draw, xpos, ypos, tmp_path): +def test_draw_methods_clip_a_shape_that_crosses_the_surface_edge(draw, xpos, ypos, tmp_path, monkeypatch): # Consumers that scroll a tiled view draw tiles straddling the edge of the # display every frame, relying on the part that lands on the surface being # painted and the rest being dropped -- not on a raise, and not on the @@ -1230,6 +1235,9 @@ def test_draw_methods_clip_a_shape_that_crosses_the_surface_edge(draw, xpos, ypo imagePath = tmp_path / "green.bmp" _write_solid_image(imagePath, (0, 255, 0)) + # Keep the mouse off every box so drawButton paints its plain color, not + # the hover lift; hover has its own tests. + monkeypatch.setattr(pygame.mouse, "get_pos", lambda: (-100, -100)) draw(graphik, imagePath, xpos, ypos) @@ -1513,7 +1521,7 @@ def test_draw_button_rejects_a_fractional_text_size(monkeypatch): with pytest.raises(TypeError): graphik.drawButton(0, 0, 40, 40, Graphik.blue, Graphik.white, 16.5, "Go", lambda: calls.append(True)) - assert _rgb(display, (5, 5)) == Graphik.blue + assert _rgb(display, (5, 5)) == BLUE_HOVER assert calls == [] @@ -1547,7 +1555,10 @@ def test_draw_button_with_fractional_bounds_hit_tests_the_unrounded_box(monkeypa graphik.drawButton(10.5, 10.5, 10.5, 10.5, Graphik.blue, Graphik.white, 10, "", lambda: calls.append(True)) assert bool(calls) == expect_call - assert (_rgb(display, pos) == Graphik.blue) == painted + # The box takes the hover color exactly when the mouse is inside the hit + # region (expect_call), so a painted pixel is one of the two blues. + boxColor = BLUE_HOVER if expect_call else Graphik.blue + assert (_rgb(display, pos) == boxColor) == painted def test_draw_button_draws_box_with_given_color(): @@ -1673,8 +1684,8 @@ def test_draw_button_with_an_empty_label_draws_a_plain_box(monkeypatch): graphik.drawButton(10, 10, 20, 20, Graphik.blue, Graphik.white, 10, "", lambda: calls.append(True)) - assert all(_rgb(display, (x, y)) == Graphik.blue for x in range(10, 30) for y in range(10, 30)) - assert _button_label_ink(display, Graphik.blue) == [] + assert all(_rgb(display, (x, y)) == BLUE_HOVER for x in range(10, 30) for y in range(10, 30)) + assert _button_label_ink(display, BLUE_HOVER) == [] assert calls == [True] @@ -1792,10 +1803,9 @@ def test_draw_button_paints_before_invoking_the_callback(monkeypatch): # The box and label are drawn first and the hit test runs last, so by the # time function() is called the button is already on the surface, and # anything the callback paints (e.g. switching to another screen) lands - # on top of it rather than being painted over. Moving the hit test ahead - # of the drawing -- say, to pick a hover color -- would leave every other - # drawButton test green while letting the button overwrite the callback's - # output in the same frame. + # on top of it rather than being painted over. The hit test now runs + # before painting to pick the hover color, so this also pins that the + # callback still fires only after the box is painted. graphik = _make_graphik((40, 40)) display = graphik.getGameDisplay() display.fill(Graphik.black) @@ -1809,8 +1819,8 @@ def callback(): graphik.drawButton(10, 10, 20, 20, Graphik.blue, Graphik.white, 10, "Go", callback) - # The box was already painted when the callback ran... - assert seenAtCallback == [Graphik.blue] + # The box was already painted (in its hover color) when the callback ran... + assert seenAtCallback == [BLUE_HOVER] # ...and nothing drawButton does afterwards paints over the callback's output. assert all(_rgb(display, (x, y)) == Graphik.green for x in range(40) for y in range(40)) @@ -1855,5 +1865,214 @@ def test_draw_button_requires_the_video_system_even_for_an_off_screen_surface(): pygame.display.init() assert pygame.display.get_surface() is None + # The mouse now reads (0, 0), inside the box, so it takes the hover color. graphik.drawButton(0, 0, 20, 20, Graphik.green, Graphik.white, 6, "", lambda: None) - assert _rgb(target, (5, 5)) == Graphik.green + assert _rgb(target, (5, 5)) == GREEN_HOVER + + +# --- hover lift (ported from Roam's vendored copy) ------------------------------ + + +@pytest.mark.parametrize( + "color, expected", + [ + pytest.param((0, 0, 200), (35, 35, 235), id="dark_lightens"), + pytest.param((240, 240, 240), (215, 215, 215), id="light_darkens"), + pytest.param((128, 128, 128), (103, 103, 103), id="average_128_counts_as_light"), + pytest.param((10, 250, 0), (45, 255, 35), id="clamped_at_255"), + pytest.param((250, 250, 10), (225, 225, 0), id="clamped_at_0"), + pytest.param((0, 0, 200, 90), (35, 35, 235, 90), id="alpha_kept"), + pytest.param([0, 0, 200], (35, 35, 235), id="list_becomes_tuple"), + ], +) +def test_hover_color(color, expected): + assert Graphik._hoverColor(color) == expected + + +def test_hover_color_accepts_a_color_name(): + assert Graphik._hoverColor("white") == pygame.Color(230, 230, 230, 255) + + +def test_draw_button_lifts_the_box_only_while_the_mouse_is_over_it(monkeypatch): + graphik = _make_graphik((40, 40)) + display = graphik.getGameDisplay() + monkeypatch.setattr(pygame.mouse, "get_pressed", lambda: (0, 0, 0)) + + monkeypatch.setattr(pygame.mouse, "get_pos", lambda: (35, 35)) + graphik.drawButton(10, 10, 20, 20, Graphik.blue, Graphik.white, 10, "", lambda: None) + assert _rgb(display, (15, 15)) == Graphik.blue + + monkeypatch.setattr(pygame.mouse, "get_pos", lambda: (15, 15)) + graphik.drawButton(10, 10, 20, 20, Graphik.blue, Graphik.white, 10, "", lambda: None) + assert _rgb(display, (15, 15)) == BLUE_HOVER + + +# --- press-only clicks via beginFrame (ported from Roam's vendored copy) -------- + + +def _frames(graphik, monkeypatch, presses, calls, pos=(15, 15)): + """Run one beginFrame/drawButton/endFrame per entry of ``presses``.""" + monkeypatch.setattr(pygame.mouse, "get_pos", lambda: pos) + for down in presses: + monkeypatch.setattr(pygame.mouse, "get_pressed", lambda d=down: (1 if d else 0, 0, 0)) + graphik.beginFrame() + graphik.drawButton(10, 10, 20, 20, Graphik.blue, Graphik.white, 10, "", lambda: calls.append(True)) + graphik.endFrame() + + +def test_without_begin_frame_a_held_button_still_fires_every_call(monkeypatch): + # The default must not change for callers that never call beginFrame. + graphik = _make_graphik((40, 40)) + calls = [] + monkeypatch.setattr(pygame.mouse, "get_pos", lambda: (15, 15)) + monkeypatch.setattr(pygame.mouse, "get_pressed", lambda: (1, 0, 0)) + for _ in range(3): + graphik.drawButton(10, 10, 20, 20, Graphik.blue, Graphik.white, 10, "", lambda: calls.append(True)) + assert calls == [True, True, True] + + +def test_with_begin_frame_a_held_button_fires_once(monkeypatch): + graphik = _make_graphik((40, 40)) + calls = [] + _frames(graphik, monkeypatch, [False, True, True, True], calls) + assert calls == [True] + + +def test_with_begin_frame_each_new_press_fires_again(monkeypatch): + graphik = _make_graphik((40, 40)) + calls = [] + _frames(graphik, monkeypatch, [False, True, False, True, True, False, True], calls) + assert calls == [True, True, True] + + +def test_with_begin_frame_a_press_outside_the_box_does_not_fire(monkeypatch): + graphik = _make_graphik((40, 40)) + calls = [] + _frames(graphik, monkeypatch, [False, True], calls, pos=(35, 35)) + assert calls == [] + + +def test_begin_frame_twice_in_one_frame_snapshots_once(monkeypatch): + # Nested screens may each call beginFrame; the second call in the same + # frame must not shift "previous" forward and swallow the press. + graphik = _make_graphik((40, 40)) + calls = [] + _frames(graphik, monkeypatch, [False], calls) + monkeypatch.setattr(pygame.mouse, "get_pressed", lambda: (1, 0, 0)) + graphik.beginFrame() + graphik.beginFrame() + graphik.drawButton(10, 10, 20, 20, Graphik.blue, Graphik.white, 10, "", lambda: calls.append(True)) + graphik.endFrame() + assert calls == [True] + + +# --- press-only robustness (from review of 0.3.0) -------------------------------- + + +def _drawGo(graphik, calls, color=Graphik.blue): + graphik.drawButton(10, 10, 20, 20, color, Graphik.white, 10, "", lambda: calls.append(True)) + + +def _press(monkeypatch, down): + monkeypatch.setattr(pygame.mouse, "get_pressed", lambda: (1 if down else 0, 0, 0)) + + +def test_a_press_already_held_when_frames_start_does_not_count(monkeypatch): + graphik = _make_graphik((40, 40)) + calls = [] + _frames(graphik, monkeypatch, [True, True, False, True], calls) + assert calls == [True] # only the fresh press in the last frame + + +@pytest.mark.parametrize( + "presses, expected", + [ + pytest.param([False, True, False, False, False, True, False], 2, id="down_then_up"), + pytest.param([False, True, True, True], 1, id="held"), + pytest.param([False, False, True, False, True], 2, id="up_first"), + ], +) +def test_frames_that_never_call_end_frame_still_click_correctly(monkeypatch, presses, expected): + # An exception or early return can skip endFrame; clicks must not get + # stuck firing every frame, or never. + graphik = _make_graphik((40, 40)) + calls = [] + monkeypatch.setattr(pygame.mouse, "get_pos", lambda: (15, 15)) + for down in presses: + _press(monkeypatch, down) + graphik.beginFrame() + _drawGo(graphik, calls) + assert len(calls) == expected + + +def test_a_draw_after_end_frame_does_not_fire_the_same_press_again(monkeypatch): + graphik = _make_graphik((40, 40)) + calls = [] + _frames(graphik, monkeypatch, [False], calls) + _press(monkeypatch, True) + graphik.beginFrame() + _drawGo(graphik, calls) + graphik.endFrame() + _drawGo(graphik, calls) + assert calls == [True] + + +def test_a_nested_loop_inside_the_callback_does_not_get_the_press(monkeypatch): + graphik = _make_graphik((40, 40)) + outer, inner = [], [] + _frames(graphik, monkeypatch, [False], []) + _press(monkeypatch, True) + + def openNestedScreen(): + outer.append(True) + for _ in range(2): # the nested screen's own frames, press still held + graphik.beginFrame() + _drawGo(graphik, inner) + graphik.endFrame() + + graphik.beginFrame() + graphik.drawButton(10, 10, 20, 20, Graphik.blue, Graphik.white, 10, "", openNestedScreen) + _drawGo(graphik, outer) # a later button in the outer frame + graphik.endFrame() + assert outer == [True] + assert inner == [] + + +def test_a_press_that_slides_onto_a_button_does_not_fire(monkeypatch): + graphik = _make_graphik((40, 40)) + calls = [] + _frames(graphik, monkeypatch, [False, True], calls, pos=(35, 35)) + _frames(graphik, monkeypatch, [True, True], calls, pos=(15, 15)) + assert calls == [] + + +def test_a_failed_begin_frame_does_not_switch_to_press_only_clicks(monkeypatch): + graphik = _make_graphik((40, 40)) + calls = [] + + def broken(): + raise pygame.error("video system not initialized") + + monkeypatch.setattr(pygame.mouse, "get_pressed", broken) + with pytest.raises(pygame.error): + graphik.beginFrame() + # Still the original mode: a held press fires on every call. + monkeypatch.setattr(pygame.mouse, "get_pos", lambda: (15, 15)) + _press(monkeypatch, True) + _drawGo(graphik, calls) + _drawGo(graphik, calls) + assert calls == [True, True] + + +def test_hover_on_a_surface_mapped_int_color_keeps_its_hue(monkeypatch): + graphik = _make_graphik((40, 40)) + display = graphik.getGameDisplay() + mapped = display.map_rgb((0, 0, 200)) + monkeypatch.setattr(pygame.mouse, "get_pos", lambda: (15, 15)) + _press(monkeypatch, False) + _drawGo(graphik, [], color=mapped) + assert _rgb(display, (15, 15)) == BLUE_HOVER + + +def test_hover_color_darkens_a_light_color_name(): + assert Graphik._hoverColor("gray60") == pygame.Color(128, 128, 128, 255)