diff --git a/README.md b/README.md index 5987f08..e017835 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ This library assists developers with graphics programming. graphik is released as git tags, not on PyPI. Install a release from its tag's archive (no `git` needed): ```bash -pip install "graphik @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.5.1.zip" +pip install "graphik @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.5.2.zip" ``` In a `requirements.txt`, use the same line without the quotes. See [RELEASING.md](RELEASING.md) for how releases are cut. @@ -95,7 +95,7 @@ and runs on Linux and Windows desktops, and in the browser under pygbag (see [In the browser](#in-the-browser)): ```bash -pip install "graphik[strata] @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.5.1.zip" +pip install "graphik[strata] @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.5.2.zip" ``` ```python @@ -133,6 +133,8 @@ So that games stop hand-building the same pieces: - **Bigger boards.** `GridBoard(columns, rows, theme, tiles=..., mergeTiles=True, viewport=...)`: `tiles` maps a cell to its own `Tile(color, raised)`; `mergeTiles` draws each row's neighbouring tiles that look the same as one box (a 64 x 64 board of one colour is 64 boxes, not 4096); `viewport=Viewport.around(column, row, reach)` draws only a window of the board, framed and fitted as if it were the whole board, with pieces and picking still in whole-board cells. - **Hover.** `board.scene(..., highlight=(column, row))` lays a thin slab in `Theme.highlight` on the tile under the pointer. - **Chains.** `board.bridgePairs(pieces)` names the joined pieces and `board.bridgeShape(a, b, aAt, bAt)` draws one bridge. +- **Phones held upright.** Since 0.5.2 `fitCamera` frames a portrait window (aspect below 1) for its shape: the camera looks down more steeply (70 degrees rather than about 55), the board fills the window's width and stands in the middle of the space below a HUD, and a large board no longer runs off the sides. Landscape and square windows keep 0.5.1's framing exactly; between an aspect of 0.8 and 1 the two blend, so a resize across square doesn't jump. `fitCamera(columns, rows, aspect, top=..., bottom=...)` (and `board.camera`, `board.scene`) keep fractions of the window's height clear at the top (a HUD) and the bottom (a bar of touch keys), in any window shape; a view takes them in pixels with `view.setInsets(top=..., bottom=...)`, and picking, `cellScreenPosition` and the web view's camera follow. +- **On-screen keys for touch screens.** `TouchKeys([TouchKey("Pause", "space"), TouchKey("Shop", "p"), ...])` lays out a bar of labelled buttons along the bottom of the screen, each at least 44 CSS pixels each way, in rows of equal buttons (up to three rows on a portrait screen, one on a landscape one; when the keys don't all fit, the last button is *More*, which pages through the rest). A tap on one, `keys.press(position, width, height, pygame, scale)`, posts the same `KEYDOWN` and `KEYUP` the keyboard would (marked `touchKey=True`), so the game's own key handling does the work in both views; a press off the bar returns `None` and is the game's. The 2D view draws the bar with `keys.draw(graphik, width, height, scale)`, the 3D view adds `keys.overlay(width, height)` (labels and panels) to its HUD, both from one `keys.layout(...)` and one hit test. Sizes are worked out in CSS pixels: `scale` is the surface's CSS pixels per pixel (1 for the web view; for a 2D canvas the browser scales, see `keys.below(width, height, pageWidth, pageHeight)`, which gives the band to add under a 2D board and the canvas's scale). `keys.bandHeight(...)` is how much of the screen the bar takes, for `view.setInsets(bottom=...)` and the HUD. Show the keys only on touch screens: `grid3d.web.touchScreen()` is true when the page sees a coarse pointer or a touch (`?touch=1` or `?touch=0` in the address says so for testing; `GRAPHIK_TOUCH=1` outside a browser). ### In the browser diff --git a/src/main/python/preponderous/graphik/_version.py b/src/main/python/preponderous/graphik/_version.py index dd9b22c..7225152 100644 --- a/src/main/python/preponderous/graphik/_version.py +++ b/src/main/python/preponderous/graphik/_version.py @@ -1 +1 @@ -__version__ = "0.5.1" +__version__ = "0.5.2" diff --git a/src/main/python/preponderous/graphik/grid3d/__init__.py b/src/main/python/preponderous/graphik/grid3d/__init__.py index bb7fc73..83aa2b8 100644 --- a/src/main/python/preponderous/graphik/grid3d/__init__.py +++ b/src/main/python/preponderous/graphik/grid3d/__init__.py @@ -11,7 +11,8 @@ Helpers shared by the 3D views of grid games: picking (pick.py: the cell under a pointer, where a point lands on screen), text in Strata's font (text.py: measure, fit, wrap, centre), screen buttons and a Graphik -stand-in for running 2D screens under a 3D view (ui.py). +stand-in for running 2D screens under a 3D view (ui.py), and a bar of +on-screen keys for touch screens, drawn alike in 2D and 3D (touchkeys.py). Importing this package imports neither Strata nor pygame. """ @@ -62,6 +63,7 @@ drawButtons, hoverColor, ) +from .touchkeys import MIN_TARGET, MORE, KeySlot, TouchKey, TouchKeys from .view import STRATA_VERSION, Grid3DView, Unavailable __all__ = [ @@ -76,5 +78,6 @@ "centredLabel", "measureText", "wrapText", "Button", "RecordedButton", "RecordedDisplay", "RecordedRect", "RecordedText", "ScreenRecorder", "drawButtons", "hoverColor", + "MIN_TARGET", "MORE", "KeySlot", "TouchKey", "TouchKeys", "STRATA_VERSION", "Grid3DView", "Unavailable", ] diff --git a/src/main/python/preponderous/graphik/grid3d/board.py b/src/main/python/preponderous/graphik/grid3d/board.py index cc81cc9..c5b068c 100644 --- a/src/main/python/preponderous/graphik/grid3d/board.py +++ b/src/main/python/preponderous/graphik/grid3d/board.py @@ -12,6 +12,7 @@ cell). `scene(highlight=...)` lights the tile under the pointer. """ +import functools import math from dataclasses import dataclass, field from typing import Callable, Dict, Hashable, List, Optional, Tuple @@ -160,11 +161,59 @@ def cellCenter(column, row, columns, rows): return (column - (columns - 1) / 2.0, row - (rows - 1) / 2.0) -def fitCamera(columns, rows, aspect=1.0, fovDegrees=42.0): - """A camera south of the board, tilted down about 55 degrees, far enough - back that the whole board and its frame fit, aiming a little beyond the - centre so the board sits low in the window and leaves the top rows of the - screen for a HUD. A tall window backs the camera off further.""" +# The camera's tilt below the horizon, in degrees: fitCamera's desktop +# framing looks down about 55 degrees; a portrait window (a phone held +# upright) looks down more steeply, so the board stands taller on screen and +# fills more of the tall, narrow window. +LANDSCAPE_PITCH = math.degrees(math.atan2(1.35, 0.95)) +PORTRAIT_PITCH = 70.0 +# Below this aspect (width / height) a window is fully "portrait"; from here +# to 1 the framing blends from portrait to the desktop's. +PORTRAIT_ASPECT = 0.8 +# How much of a portrait window's height is kept free for a HUD at the top +# (and a little at the bottom) when the caller doesn't say, and the margins +# kept inside whatever area the board is fitted to. +DEFAULT_TOP, DEFAULT_BOTTOM = 0.12, 0.03 +SIDE_MARGIN, END_MARGIN = 0.02, 0.02 + + +def fitCamera(columns, rows, aspect=1.0, fovDegrees=42.0, top=None, bottom=None): + """A camera south of the board, looking down at it, far enough back that + the whole board and its frame fit. + + A landscape (or square) window with nothing reserved keeps the desktop + framing: tilted down about 55 degrees, aiming a little beyond the centre + so the board sits low in the window and leaves the top rows of the screen + for a HUD. + + A portrait window (aspect below 1, a phone held upright) is framed for its + shape instead: the camera looks down more steeply and the board fills the + window's width and stands in the middle of the space left between `top` + and `bottom`. Between PORTRAIT_ASPECT and 1 the two framings blend, so + resizing a window across square doesn't make the board jump. + + `top` and `bottom` are the fractions (0-1) of the window's height kept + clear of the board: a HUD across the top, a bar of touch keys at the + bottom. Given either (in any window shape), the board is fitted inside + the space between them. Left out, a portrait window keeps DEFAULT_TOP and + DEFAULT_BOTTOM clear and a landscape one is framed as on the desktop.""" + aspect = max(float(aspect), 0.05) + reserved = top is not None or bottom is not None + if not reserved and aspect >= 1.0: + return _desktopCamera(columns, rows, aspect, fovDegrees) + portrait = _portraitWeight(aspect) + pitch = LANDSCAPE_PITCH + (PORTRAIT_PITCH - LANDSCAPE_PITCH) * portrait + top = DEFAULT_TOP if top is None else top + bottom = DEFAULT_BOTTOM if bottom is None else bottom + fitted = _fittedCamera(columns, rows, aspect, fovDegrees, pitch, top, bottom) + if reserved or portrait >= 1.0: + return fitted + # a nearly square window: part way from the desktop framing to this one + return _blendCameras(_desktopCamera(columns, rows, aspect, fovDegrees), fitted, portrait) + + +def _desktopCamera(columns, rows, aspect, fovDegrees): + # graphik 0.5.1's framing, unchanged for landscape windows size = max(columns, rows) + 1.0 # the frame adds about half a cell a side size *= max(1.0, 1.0 / max(aspect, 0.5)) distance = 0.86 * size + 0.9 @@ -175,6 +224,101 @@ def fitCamera(columns, rows, aspect=1.0, fovDegrees=42.0): ) +def _portraitWeight(aspect): + """0 for a landscape or square window, 1 at PORTRAIT_ASPECT and below.""" + if aspect >= 1.0: + return 0.0 + if aspect <= PORTRAIT_ASPECT: + return 1.0 + return (1.0 - aspect) / (1.0 - PORTRAIT_ASPECT) + + +def _blendCameras(a, b, weight): + mix = lambda p, q: tuple(x + (y - x) * weight for x, y in zip(p, q)) # noqa: E731 + return Camera(eye=mix(a.eye, b.eye), target=mix(a.target, b.target), + fovDegrees=a.fovDegrees + (b.fovDegrees - a.fovDegrees) * weight) + + +# what fitCamera keeps in view: the board's tiles and frame (half a cell +# past its edge, less a little), from under the tiles to the height of a +# typical piece +_EDGE, _LOW, _HIGH = 0.35, -0.18, 0.5 + + +def _boardExtent(columns, rows, eye, forward, right, up, focal, aspect): + """The board's bounding box on screen, in normalised device + coordinates: (left, bottom, right, top).""" + xs, ys = [], [] + for x in (-columns / 2.0 - _EDGE, columns / 2.0 + _EDGE): + for z in (-rows / 2.0 - _EDGE, rows / 2.0 + _EDGE): + for y in (_LOW, _HIGH): + d = (x - eye[0], y - eye[1], z - eye[2]) + depth = d[0] * forward[0] + d[1] * forward[1] + d[2] * forward[2] + if depth <= 1e-6: + return None + xs.append(focal / aspect * (d[0] * right[0] + d[1] * right[1] + d[2] * right[2]) / depth) + ys.append(focal * (d[0] * up[0] + d[1] * up[1] + d[2] * up[2]) / depth) + return min(xs), min(ys), max(xs), max(ys) + + +@functools.lru_cache(maxsize=256) +def _fittedCamera(columns, rows, aspect, fovDegrees, pitch, top, bottom): + """The camera at `pitch` degrees below the horizon that shows the board + as big as it fits, with SIDE_MARGIN at the sides and END_MARGIN above + and below, in the window's height between `top` and `bottom` (fractions + of it), centred in that space.""" + top = min(max(float(top), 0.0), 0.9) + bottom = min(max(float(bottom), 0.0), 0.9 - top) + # the space the board may fill, in normalised device coordinates (y up) + ndcTop = 1.0 - 2.0 * (top + END_MARGIN) + ndcBottom = -1.0 + 2.0 * (bottom + END_MARGIN) + if ndcTop - ndcBottom < 0.1: + ndcTop, ndcBottom = 0.05, -0.05 + ndcWidth = 2.0 * (1.0 - 2.0 * SIDE_MARGIN) + middle = (ndcTop + ndcBottom) / 2.0 + tilt = math.radians(pitch) + back = (0.0, math.sin(tilt), math.cos(tilt)) # from the target to the eye + forward = (0.0, -back[1], -back[2]) + right = (1.0, 0.0, 0.0) + up = (0.0, back[2], -back[1]) # right x forward + focal = 1.0 / math.tan(math.radians(fovDegrees) / 2.0) + + def extent(distance, shift): + # the target slides along the board's depth (z) by `shift` + eye = (0.0, distance * back[1], shift + distance * back[2]) + return _boardExtent(columns, rows, eye, forward, right, up, focal, aspect) + + def centred(distance): + # the shift that puts the board's middle in the middle of the space + low, high = -4.0 * (rows + columns) - 10.0, 4.0 * (rows + columns) + 10.0 + for _ in range(36): + shift = (low + high) / 2.0 + box = extent(distance, shift) + if box is not None and (box[1] + box[3]) / 2.0 < middle: + # the camera moving south (larger z) raises the board on screen + low = shift + else: + high = shift + return (low + high) / 2.0 + + def fits(distance): + shift = centred(distance) + box = extent(distance, shift) + return box is not None and box[2] - box[0] <= ndcWidth and box[3] - box[1] <= ndcTop - ndcBottom + + near, far = 0.5, 10.0 * (columns + rows) + 20.0 + for _ in range(36): + distance = (near + far) / 2.0 + if fits(distance): + far = distance + else: + near = distance + shift = centred(far) + target = (0.0, 0.0, shift) + eye = (0.0, far * back[1], shift + far * back[2]) + return Camera(eye=eye, target=target, fovDegrees=fovDegrees) + + class GridBoard: """A columns x rows board drawn with a Theme. @@ -232,9 +376,11 @@ def cellCenter(self, column, row): def contains(self, column, row): return 0 <= column < self.columns and 0 <= row < self.rows - def camera(self, aspect=1.0): + def camera(self, aspect=1.0, top=None, bottom=None): + """fitCamera for what is on show; `top` and `bottom` are the + fractions of the window's height kept clear of the board.""" columns, rows = self.shownSize() - return fitCamera(columns, rows, aspect) + return fitCamera(columns, rows, aspect, top=top, bottom=bottom) def cellAt(self, x, z): """The visible board cell under world point (x, z), or None.""" @@ -446,11 +592,13 @@ def _bridges(self, pieces, where): def scene(self, pieces=(), positions=None, labels=(), panels=(), lights=(), aspect=1.0, tint=None, clearColor=None, highlight=None, - highlightColor=None): + highlightColor=None, top=None, bottom=None): """A complete Scene, checked against the engine limits. `highlight` - is a (column, row) whose tile gets the hover slab, drawn last.""" + is a (column, row) whose tile gets the hover slab, drawn last. + `top` and `bottom` are the fractions of the window's height the + camera keeps clear of the board (see fitCamera).""" pieceShapes, pieceLights = self.pieceShapes(pieces, positions) - scene = Scene(camera=self.camera(aspect)) + scene = Scene(camera=self.camera(aspect, top=top, bottom=bottom)) scene.shapes = (self.boardShapes(tint) + pieceShapes + self.highlightShapes(highlight, highlightColor)) scene.lights = list(lights) + pieceLights diff --git a/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl b/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl index 9569582..8a40f05 100644 --- a/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl +++ b/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl @@ -473,7 +473,8 @@ frameborder="1" (function () { "use strict"; // window.Graphik3D: the page's 2D/3D switch, read by grid3d.web.wants3D() - // and set by grid3d.web.set3D(); its area() by grid3d.web.buttonArea(). + // and set by grid3d.web.set3D(); its area() by grid3d.web.buttonArea(), + // its touch() by grid3d.web.touchScreen(). // Strings and numbers only (pygbag's bridge). const button = document.getElementById("graphik3d"); const note = document.getElementById("graphik3d-note"); @@ -623,6 +624,17 @@ frameborder="1" const c = on ? canvas3d() : canvas2d(); if (c && c.focus) c.focus(); }); + // A touch screen: a coarse pointer, or a touch already seen (a laptop's + // touch screen), unless the address says ?touch=0 or ?touch=1. + let touchSeen = false; + window.addEventListener("touchstart", function () { touchSeen = true; }, {capture: true, passive: true}); + function touchScreen() { + let asked = ""; + try { asked = new URLSearchParams(window.location.search).get("touch") || ""; } catch (e) { asked = ""; } + if (asked === "1" || asked === "0") return Number(asked); + if (touchSeen) return 1; + try { return window.matchMedia("(pointer: coarse)").matches ? 1 : 0; } catch (e) { return 0; } + } window.Graphik3D = { // on, and the relay's scripts are in (so Grid3DWebView.open() can begin) wanted: function () { return on && scripts === "ready" ? 1 : 0; }, @@ -638,6 +650,8 @@ frameborder="1" if (!r.width || !r.height) return ""; return [r.left, r.top, r.width, r.height].map(function (v) { return Math.round(v); }).join(","); }, + // 1 on a touch screen, where a game shows its on-screen keys + touch: touchScreen, }; label(); if (startingView() === "3d") { diff --git a/src/main/python/preponderous/graphik/grid3d/touchkeys.py b/src/main/python/preponderous/graphik/grid3d/touchkeys.py new file mode 100644 index 0000000..e6e7843 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/touchkeys.py @@ -0,0 +1,263 @@ +"""On-screen keys for touch screens: a bar of labelled buttons that press keys. + +A phone has no keyboard, so a game's keyboard-only actions (pause, a shop, +restart) can't be reached there. TouchKeys lays out a bar of buttons along +the bottom of the screen, one per key, and a tap on one posts the same +pygame KEYDOWN and KEYUP events the keyboard would, so the game's own key +handling does the work, whichever view shows: the 2D view draws the bar +with Graphik, the 3D view as screen Buttons (Labels and Panels), from one +layout, with one hit test. + +The layout is worked out in CSS pixels (where a touch target is at least +MIN_TARGET, 44, pixels each way, as phones' guidelines ask) and handed back +in the pixels of the surface it is drawn on: the 3D view's are CSS pixels +already (`scale` 1); a 2D canvas the browser scales to fit the page has +`scale` CSS pixels per canvas pixel. Keys fill rows of equal buttons, at +most `portraitRows` rows on a portrait screen and `landscapeRows` on a +landscape one; when they don't all fit, the last button is "More", which +pages through the rest (a compact menu that never covers the board). + +The bar takes bandHeight() pixels at the bottom of the screen. A 3D view +keeps them clear of the board (Grid3DView.setInsets(bottom=...)); a 2D game +makes its window that much taller (below()) and draws its board above it. + +Show the keys only on touch screens: web.touchScreen() says whether the page +sees one. Pure Python: pygame and a Graphik are passed in. +""" + +import math +from dataclasses import dataclass +from typing import Optional + +from .scene import Panel, rgb255, rgba +from .text import measureText +from .ui import Button, contains, hoverColor + +MIN_TARGET = 44 # CSS pixels: the smallest button a finger is sure to hit +MORE = "more" # what press() returns for the More button + + +# key names (pygame.key.name's spellings) and the character a key types +_UNICODE = {"space": " ", "return": "\r", "escape": "\x1b", "tab": "\t", "backspace": "\b"} + + +@dataclass(frozen=True) +class TouchKey: + """One on-screen key: its `label` and the key it presses, by pygame's + name for it ("p", "space", "[", "up", "return", "escape", "f11").""" + + label: str + key: str + + def unicode(self): + """The character the key types, as a KEYDOWN's `unicode` ("" for + keys that type none, such as the arrows).""" + if len(self.key) == 1: + return self.key + return _UNICODE.get(self.key, "") + + +@dataclass +class KeySlot: + """A button of the bar as laid out: its box in the surface's pixels, its + label, and its TouchKey (None for the More button).""" + + x: float + y: float + width: float + height: float + label: str + key: Optional[TouchKey] + + def contains(self, position): + # the drawn box exactly, with Graphik.drawButton's edges + return contains(self.x, self.y, self.width, self.height, position) + + +class TouchKeys: + """A bar of on-screen keys (see the module's notes). + + `keys` are TouchKeys (or (label, key) pairs). Sizes are CSS pixels: + each button is at least `minTarget` each way and wide enough for its + label at `pixelSize` plus `padding` a side, with `gap` between buttons + and `margin` around the bar. Colours are 0-255 (r, g, b), as Graphik + takes them; the 3D view draws the buttons at `alpha` and the bar behind + them in `barColor` at `barAlpha`. + """ + + def __init__(self, keys=(), minTarget=MIN_TARGET, gap=6, margin=8, pixelSize=11, padding=6, + portraitRows=3, landscapeRows=1, color=(34, 34, 34), textColor=(238, 238, 238), + barColor=(10, 10, 14), alpha=0.9, barAlpha=0.55, moreLabel="More", backLabel="Back"): + self.minTarget, self.gap, self.margin = minTarget, gap, margin + self.pixelSize, self.padding = pixelSize, padding + self.portraitRows, self.landscapeRows = portraitRows, landscapeRows + self.color, self.textColor, self.barColor = color, textColor, barColor + self.alpha, self.barAlpha = alpha, barAlpha + self.moreLabel, self.backLabel = moreLabel, backLabel + self.keys = () + self.page = 0 + self._pages = 1 + self.setKeys(keys) + + def setKeys(self, keys): + """Changes the keys on offer (a game's shop has others than its + board); back to the first page when they change.""" + keys = tuple(k if isinstance(k, TouchKey) else TouchKey(*k) for k in keys) + if keys != self.keys: + self.keys = keys + self.page = 0 + + # -- the layout + + def _grid(self, cssWidth, cssHeight, portrait): + """(columns, rows, pages, perPage) for a screen this size in CSS + pixels.""" + if not self.keys: + return 0, 0, 0, 0 + widest = max(measureText(k.label, self.pixelSize) for k in self.keys) + widest = max(widest, measureText(self.moreLabel, self.pixelSize), + measureText(self.backLabel, self.pixelSize)) + cell = max(self.minTarget, widest + 2 * self.padding) + room = cssWidth - 2 * self.margin + self.gap + columns = max(1, int(room // (cell + self.gap))) + if portrait is None: + portrait = cssHeight > cssWidth + maxRows = max(1, self.portraitRows if portrait else self.landscapeRows) + count = len(self.keys) + if count <= columns * maxRows: + columns = min(columns, count) + return columns, int(math.ceil(count / float(columns))), 1, count + perPage = columns * maxRows - 1 # the last button is More + if perPage < 1: + perPage = 1 + return columns, maxRows, int(math.ceil(count / float(perPage))), perPage + + def bandHeight(self, width, height, scale=1.0, portrait=None): + """How many of the surface's pixels the bar takes at the bottom of a + `width` x `height` surface (0 with no keys).""" + _, rows, _, _ = self._grid(width * scale, height * scale, portrait) + if not rows: + return 0 + css = rows * self.minTarget + (rows - 1) * self.gap + 2 * self.margin + return css / float(scale) + + def layout(self, width, height, scale=1.0, portrait=None): + """The buttons on show (this page's), as KeySlots in the surface's + pixels, in rows along the bottom of a `width` x `height` surface. + `portrait` says how many rows the bar may take (default: the + surface's own shape).""" + cssWidth, cssHeight = width * scale, height * scale + columns, rows, pages, perPage = self._grid(cssWidth, cssHeight, portrait) + self._pages = pages + if not columns: + return [] + self.page %= pages + shown = list(self.keys[self.page * perPage:(self.page + 1) * perPage]) + if pages > 1: + shown.append(None) + cellWidth = (cssWidth - 2 * self.margin - (columns - 1) * self.gap) / float(columns) + top = cssHeight - self.margin - rows * self.minTarget - (rows - 1) * self.gap + slots = [] + for index, key in enumerate(shown): + row, column = divmod(index, columns) + x = self.margin + column * (cellWidth + self.gap) + y = top + row * (self.minTarget + self.gap) + if key is None: + label = self.backLabel if self.page == pages - 1 else self.moreLabel + else: + label = key.label + slots.append(KeySlot(x / scale, y / scale, cellWidth / scale, self.minTarget / scale, + label, key)) + return slots + + def below(self, width, height, pageWidth, pageHeight): + """For a 2D game: (band, scale) for a `width` x `height` board with + the bar below it, the whole (width x height + band) canvas fitted to + a `pageWidth` x `pageHeight` page as the browser does (`scale` is + its CSS pixels per canvas pixel). The bar's buttons are then at + least `minTarget` CSS pixels each way.""" + portrait = pageHeight > pageWidth + scale = min(pageWidth / float(width), pageHeight / float(height)) + for _ in range(4): + bandCss = self.bandHeight(width, height, scale, portrait) * scale + # the canvas is fitted by its width, or by its height with the + # band's CSS pixels below the board's + scale = min(pageWidth / float(width), max(pageHeight - bandCss, 1.0) / float(height)) + band = int(math.ceil(bandCss / scale)) if bandCss else 0 + return band, min(pageWidth / float(width), pageHeight / float(height + band)) + + # -- presses + + def slotAt(self, position, width, height, scale=1.0, portrait=None): + """The KeySlot under `position`, or None.""" + for slot in self.layout(width, height, scale, portrait): + if slot.contains(position): + return slot + return None + + def press(self, position, width, height, pygame=None, scale=1.0, portrait=None): + """A press at `position`: on a key, its KEYDOWN and KEYUP are posted + to pygame's queue (when `pygame` is given) and its TouchKey + returned; on More, the next page shows and MORE is returned; off + the bar, None (the press is the game's).""" + slot = self.slotAt(position, width, height, scale, portrait) + if slot is None: + return None + if slot.key is None: + self.page = (self.page + 1) % max(1, self._pages) + return MORE + if pygame is not None: + for event in self.keyEvents(slot.key, pygame): + pygame.event.post(event) + return slot.key + + @staticmethod + def keyEvents(key, pygame): + """The KEYDOWN and KEYUP a keyboard sends for `key` (a TouchKey), + marked touchKey=True.""" + code = pygame.key.key_code(key.key) + down = pygame.event.Event(pygame.KEYDOWN, key=code, mod=0, scancode=0, + unicode=key.unicode(), touchKey=True) + up = pygame.event.Event(pygame.KEYUP, key=code, mod=0, scancode=0, touchKey=True) + return [down, up] + + # -- drawing + + def draw(self, graphik, width, height, scale=1.0, portrait=None, pointer=None): + """The bar in a 2D view, drawn with `graphik` (a Graphik) on its + surface: the band, then each button, lifted under `pointer`.""" + slots = self.layout(width, height, scale, portrait) + if not slots: + return slots + band = self.bandHeight(width, height, scale, portrait) + top = int(math.floor(height - band)) # to the last row of pixels + graphik.drawRectangle(0, top, int(math.ceil(width)), int(math.ceil(height)) - top, + self.barColor) + size = max(8, int(round(self.pixelSize * 1.15 / scale))) + for slot in slots: + box = hoverColor(self.color) if slot.contains(pointer) else self.color + graphik.drawRectangle(slot.x, slot.y, slot.width, slot.height, box) + graphik.drawText(slot.label, slot.x + slot.width / 2.0, slot.y + slot.height / 2.0, + size, self.textColor) + return slots + + def buttons(self, width, height, portrait=None): + """The bar's buttons in a 3D view (CSS pixels), as ui.Buttons.""" + return [Button(s.x, s.y, s.width, s.height, s.label, color=self.color, + textColor=self.textColor, pixelSize=self.pixelSize, alpha=self.alpha) + for s in self.layout(width, height, 1.0, portrait)] + + def overlay(self, width, height, portrait=None, pointer=None): + """The bar in a 3D view: (labels, panels) to add to its HUD, the + band's panel first.""" + buttons = self.buttons(width, height, portrait) + if not buttons: + return [], [] + band = self.bandHeight(width, height, 1.0, portrait) + labels, panels = [], [Panel(0, height - band, width, band, + rgba(rgb255(self.barColor), self.barAlpha))] + for button in buttons: + panel, label = button.draw(pointer) + panels.append(panel) + labels.append(label) + return labels, panels diff --git a/src/main/python/preponderous/graphik/grid3d/view.py b/src/main/python/preponderous/graphik/grid3d/view.py index 1e02b50..e4cf2f8 100644 --- a/src/main/python/preponderous/graphik/grid3d/view.py +++ b/src/main/python/preponderous/graphik/grid3d/view.py @@ -69,11 +69,36 @@ class ViewGeometry: """Where things are on screen, for a view with `board`, `width` and `height` (Grid3DView and Grid3DWebView).""" + # pixels at the top and bottom of the window kept clear of the board + # (setInsets); None for fitCamera's own framing + insets = None + + def setInsets(self, top=None, bottom=None): + """Keeps `top` pixels at the top of the window (a HUD) and `bottom` + at the bottom (a bar of touch keys) clear of the board: the camera + fits the board in the space between. None for both (the default) + frames the board as fitCamera does for the window's shape. Returns + whether anything changed.""" + insets = None if top is None and bottom is None else (top or 0, bottom or 0) + if insets == self.insets: + return False + self.insets = insets + return True + + def insetFractions(self): + """(top, bottom) as fractions of the window's height, or (None, + None) when no insets are set.""" + if self.insets is None or not self.height: + return None, None + top, bottom = self.insets + return top / float(self.height), bottom / float(self.height) + def camera(self): """The camera the current board is drawn with at this window size.""" if self.board is None: raise RuntimeError("setBoard() must come before the camera") - return self.board.camera(self.width / float(self.height)) + top, bottom = self.insetFractions() + return self.board.camera(self.width / float(self.height), top=top, bottom=bottom) def pickCell(self, x, y): """The board (column, row) under window pixel (x, y), or None.""" @@ -185,6 +210,8 @@ def scene(self, now=None): lights=self.boardLights, aspect=self.width / float(self.height), tint=self.boardTint, + top=self.insetFractions()[0], + bottom=self.insetFractions()[1], ) def frame(self, now=None, present=True): diff --git a/src/main/python/preponderous/graphik/grid3d/web.py b/src/main/python/preponderous/graphik/grid3d/web.py index a74fd19..2917abd 100644 --- a/src/main/python/preponderous/graphik/grid3d/web.py +++ b/src/main/python/preponderous/graphik/grid3d/web.py @@ -35,7 +35,9 @@ game keeps its 2D canvas, and the page says why, whenever the 3D view can't start; a page starting in 2D fetches nothing of the 3D view until the button is pressed. The button sits in the page's top right corner; -buttonArea() says where, so a game's HUD can stay out from under it. +buttonArea() says where, so a game's HUD can stay out from under it, and +touchScreen() whether the page is on a touch screen, where a game shows its +on-screen keys (touchkeys.py). Pure Python (struct, base64, json); pygbag's `platform` only in a browser. """ @@ -415,6 +417,22 @@ def buttonArea(): return None +def touchScreen(): + """True when the page is on a touch screen (a phone, a tablet), where + a game shows its on-screen keys (touchkeys.TouchKeys): the template's + Graphik3D.touch() says so for a coarse pointer, once the page has seen + a touch, or when the address says ?touch=1 (?touch=0 says not). False + outside a browser, unless the GRAPHIK_TOUCH environment variable is 1 + (for trying the keys on a desktop), and on a page without the button.""" + toggle = pageObject("Graphik3D") + if toggle is None: + return sys.platform != "emscripten" and os.environ.get("GRAPHIK_TOUCH") == "1" + try: + return bool(int(toggle.touch())) + except Exception: # an older template, without touch() + return False + + def set3D(on, reason=""): """Turns the page's 3D toggle on or off (off with a `reason` marks it unavailable, e.g. after Unavailable). Does nothing outside a browser.""" @@ -533,9 +551,11 @@ def scene(self, now=None): if self.board is None: raise RuntimeError("setBoard() must come before drawing") now = self.clock() if now is None else now + top, bottom = self.insetFractions() return self.board.scene(self.pieces, positions=self.animator.positions(now), labels=self.labels, panels=self.panels, lights=self.boardLights, - aspect=self.width / float(self.height), tint=self.boardTint) + aspect=self.width / float(self.height), tint=self.boardTint, + top=top, bottom=bottom) def frame(self, now=None, present=True): """Nothing to do per frame: the relay draws on the page's own frames.""" @@ -571,6 +591,14 @@ def resize(self, width, height): self.width, self.height = width, height self._sendView() + def setInsets(self, top=None, bottom=None): + """As Grid3DView's (ViewGeometry.setInsets); the page is sent the + new camera at once.""" + changed = super().setInsets(top, bottom) + if changed: + self._sendView() + return changed + def savePng(self, path): raise Unavailable("screenshots of the web view are taken by the page (canvas.toBlob)") diff --git a/src/test/python/preponderous/graphik/grid3d/test_grid3d_touch.py b/src/test/python/preponderous/graphik/grid3d/test_grid3d_touch.py new file mode 100644 index 0000000..ae044fe --- /dev/null +++ b/src/test/python/preponderous/graphik/grid3d/test_grid3d_touch.py @@ -0,0 +1,380 @@ +"""Phones: the board framed for a portrait screen (fitCamera, the views' +insets) and the on-screen keys (touchkeys.TouchKeys), drawn alike in 2D +and 3D. No GPU; pygame only for its events and a Graphik on a surface.""" + +import sys +import types + +import pygame +import pytest + +from preponderous.graphik import Graphik +from preponderous.graphik.grid3d import ( + MIN_TARGET, + MORE, + GridBoard, + TouchKey, + TouchKeys, + fitCamera, + projectToScreen, +) +from preponderous.graphik.grid3d import board as boardModule +from preponderous.graphik.grid3d import web +from preponderous.graphik.grid3d.view import ViewGeometry + +SIZES = [(390, 844), (844, 390), (800, 600), (1280, 800), (900, 700), (430, 932), (600, 800)] + + +def boardBox(camera, columns, rows, width, height): + """The board's (frame included) bounding box on screen: (left, top, + right, bottom) in pixels.""" + points = [] + for x in (-columns / 2.0 - 0.35, columns / 2.0 + 0.35): + for z in (-rows / 2.0 - 0.35, rows / 2.0 + 0.35): + for y in (-0.18, 0.3): + points.append(projectToScreen(camera, (x, y, z), width, height)) + xs = [p[0] for p in points] + ys = [p[1] for p in points] + return min(xs), min(ys), max(xs), max(ys) + + +def share(box, width, height): + """The share of the screen the box covers (what is off screen doesn't + count).""" + left, top, right, bottom = box + left, top, right, bottom = max(left, 0), max(top, 0), min(right, width), min(bottom, height) + return (right - left) * (bottom - top) / float(width * height) + + +# -- framing + + +def test_landscape_and_desktop_framing_is_unchanged(): + # graphik 0.5.1's formula, for every landscape or square window + for columns, rows in [(4, 3), (5, 5), (16, 16), (64, 64), (20, 8)]: + for width, height in [(844, 390), (800, 600), (1280, 800), (900, 700), (700, 700)]: + aspect = width / float(height) + size = (max(columns, rows) + 1.0) * max(1.0, 1.0 / max(aspect, 0.5)) + distance = 0.86 * size + 0.9 + camera = fitCamera(columns, rows, aspect) + assert camera.eye == (0.0, 1.35 * distance, 0.95 * distance) + assert camera.target == (0.0, -0.3, -0.04 * size) + + +@pytest.mark.parametrize("columns, rows", [(3, 3), (5, 5), (4, 3), (16, 16), (64, 64), (20, 8), (8, 20)]) +@pytest.mark.parametrize("width, height", SIZES) +def test_the_whole_board_is_on_screen_at_every_aspect(columns, rows, width, height): + box = boardBox(fitCamera(columns, rows, width / float(height)), columns, rows, width, height) + left, top, right, bottom = box + assert left >= 0 and right <= width and top >= 0 and bottom <= height + + +@pytest.mark.parametrize("columns, rows", [(3, 3), (5, 5), (16, 16), (64, 64)]) +def test_a_portrait_phone_fills_its_width_and_centres_the_board(columns, rows): + width, height = 390, 844 + camera = fitCamera(columns, rows, width / float(height)) + left, top, right, bottom = boardBox(camera, columns, rows, width, height) + assert right - left >= 0.9 * width # the board fills the width + # in the middle of the space below the default HUD room + middle = (top + bottom) / 2.0 + space = (boardModule.DEFAULT_TOP * height, height - boardModule.DEFAULT_BOTTOM * height) + # (fitCamera centres the board with a piece's height on it; this box has less) + assert abs(middle - (space[0] + space[1]) / 2.0) < 8 + # it stands taller than 0.5.1's framing made it, and no lower + old = boardModule._desktopCamera(columns, rows, width / float(height), 42.0) + oldBox = boardBox(old, columns, rows, width, height) + assert bottom - top > oldBox[3] - oldBox[1] + # bigger on screen, unless 0.5.1's ran off the sides + assert share((left, top, right, bottom), width, height) > share(oldBox, width, height) \ + or oldBox[0] < 0 or oldBox[2] > width + + +def test_a_portrait_camera_looks_down_more_steeply(): + portrait = fitCamera(5, 5, 390 / 844.0) + desktop = fitCamera(5, 5, 900 / 700.0) + + def pitch(camera): + import math + + dy = camera.eye[1] - camera.target[1] + dz = camera.eye[2] - camera.target[2] + return math.degrees(math.atan2(dy, dz)) + + assert pitch(portrait) == pytest.approx(boardModule.PORTRAIT_PITCH, abs=0.01) + assert pitch(desktop) == pytest.approx(boardModule.LANDSCAPE_PITCH, abs=0.5) + + +@pytest.mark.parametrize("width, height", SIZES) +def test_reserved_space_at_the_top_and_bottom_is_kept_clear(width, height): + top, bottom = 0.12, 0.2 + camera = fitCamera(6, 6, width / float(height), top=top, bottom=bottom) + left, boxTop, right, boxBottom = boardBox(camera, 6, 6, width, height) + assert boxTop >= top * height - 1 + assert boxBottom <= height - bottom * height + 1 + assert left >= 0 and right <= width + # and the board fills that space one way or the other + room = (height * (1 - top - bottom), width) + assert boxBottom - boxTop >= 0.9 * room[0] * (1 - 2 * boardModule.END_MARGIN) or \ + right - left >= 0.9 * room[1] * (1 - 2 * boardModule.SIDE_MARGIN) + + +def test_nearly_square_windows_blend_without_a_jump(): + def eye(aspect): + return fitCamera(5, 5, aspect).eye + + square = eye(1.0) + almost = eye(0.999) + assert all(abs(a - b) < 0.2 for a, b in zip(square, almost)) + # and the blend reaches the portrait framing at PORTRAIT_ASPECT + assert fitCamera(5, 5, boardModule.PORTRAIT_ASPECT) == boardModule._fittedCamera( + 5, 5, boardModule.PORTRAIT_ASPECT, 42.0, boardModule.PORTRAIT_PITCH, + boardModule.DEFAULT_TOP, boardModule.DEFAULT_BOTTOM) + + +class Geometry(ViewGeometry): + def __init__(self, width, height): + self.width, self.height = width, height + self.board = GridBoard(5, 5) + + +def test_a_views_insets_reach_its_camera_and_picking(): + view = Geometry(390, 844) + plain = view.camera() + assert view.setInsets(top=100, bottom=180) is True + assert view.setInsets(top=100, bottom=180) is False + assert view.insetFractions() == (100 / 844.0, 180 / 844.0) + framed = view.camera() + assert framed != plain + assert framed == fitCamera(5, 5, 390 / 844.0, top=100 / 844.0, bottom=180 / 844.0) + # a press on a tile's middle picks it, with the insets' camera + x, y = view.cellScreenPosition(2, 4) + assert view.pickCell(x, y) == (2, 4) + assert view.setInsets() is True and view.camera() == plain + + +def test_the_web_view_sends_the_new_camera_when_its_insets_change(): + relay = web.RecordingRelay() + view = web.Grid3DWebView.open(390, 844, relay=relay) + view.setBoard(GridBoard(5, 5)) + sent = len(relay.messages) + view.setInsets(top=90, bottom=170) + assert len(relay.messages) == sent + 1 + kind, body = web.decode(relay.messages[-1]) + assert kind == web.VIEW + camera = fitCamera(5, 5, 390 / 844.0, top=90 / 844.0, bottom=170 / 844.0) + assert body["eye"] == pytest.approx(camera.eye, abs=1e-4) + view.setInsets(top=90, bottom=170) + assert len(relay.messages) == sent + 1 # nothing changed, nothing sent + assert view.scene().camera == camera + + +# -- the keys + + +OPHIDIAN = [("Pause", "space"), ("Shop", "p"), ("Retry", "r"), ("Skin", "c"), ("Speed", "l")] +MANY = [("K%d" % i, "abcdefghijklmnopqrstuvwxyz"[i]) for i in range(19)] + + +def test_a_few_keys_make_one_row_of_equal_buttons_at_the_bottom(): + keys = TouchKeys(OPHIDIAN) + slots = keys.layout(390, 844) + assert [s.label for s in slots] == ["Pause", "Shop", "Retry", "Skin", "Speed"] + assert len({s.y for s in slots}) == 1 and len({round(s.width, 6) for s in slots}) == 1 + band = keys.bandHeight(390, 844) + assert band == MIN_TARGET + 2 * 8 + for slot in slots: + assert slot.width >= MIN_TARGET and slot.height >= MIN_TARGET + assert slot.y >= 844 - band and slot.y + slot.height <= 844 + assert slot.x >= 0 and slot.x + slot.width <= 390 + + +@pytest.mark.parametrize("width, height", SIZES) +def test_buttons_never_overlap_and_stay_on_screen(width, height): + keys = TouchKeys(MANY) + slots = keys.layout(width, height) + for a in slots: + assert a.width >= MIN_TARGET and a.height >= MIN_TARGET + assert a.x >= 0 and a.x + a.width <= width and a.y + a.height <= height + for b in slots: + if a is not b: + assert not (a.x < b.x + b.width and b.x < a.x + a.width + and a.y < b.y + b.height and b.y < a.y + a.height) + + +def test_too_many_keys_page_through_more(): + keys = TouchKeys(MANY) + # a landscape phone: one row, the last button More + seen = [] + for page in range(5): + slots = keys.layout(844, 390) + assert len({s.y for s in slots}) == 1 + assert slots[-1].key is None + seen += [s.key.key for s in slots if s.key is not None] + assert keys.press((slots[-1].x + 1, slots[-1].y + 1), 844, 390) == MORE + assert set(seen) == {key for _, key in MANY} + assert keys.layout(844, 390)[-1].label in ("More", "Back") + # portrait: up to three rows + keys.page = 0 + slots = keys.layout(390, 844) + assert len({s.y for s in slots}) <= 3 + + +def test_the_last_page_says_back(): + keys = TouchKeys(MANY) + labels = [] + for _ in range(10): + slots = keys.layout(844, 390) + labels.append(slots[-1].label) + keys.press((slots[-1].x + 1, slots[-1].y + 1), 844, 390) + if keys.page == 0: + break + assert labels[-1] == "Back" and set(labels[:-1]) == {"More"} + + +def test_new_keys_start_on_the_first_page(): + keys = TouchKeys(MANY) + keys.page = 2 + keys.setKeys(MANY) + assert keys.page == 2 # the same keys + keys.setKeys(OPHIDIAN) + assert keys.page == 0 + + +def test_a_press_on_a_key_posts_the_keyboards_keydown_and_keyup(): + pygame.display.init() + try: + pygame.event.clear() + keys = TouchKeys(OPHIDIAN) + slot = keys.layout(390, 844)[0] # Pause + assert keys.press((slot.x + 5, slot.y + 5), 390, 844, pygame) == TouchKey("Pause", "space") + down, up = pygame.event.get([pygame.KEYDOWN, pygame.KEYUP]) + assert down.type == pygame.KEYDOWN and down.key == pygame.K_SPACE and down.unicode == " " + assert up.type == pygame.KEYUP and up.key == pygame.K_SPACE + assert down.touchKey and up.touchKey + # off the bar: the press is the game's + assert keys.press((195, 300), 390, 844, pygame) is None + assert pygame.event.get([pygame.KEYDOWN]) == [] + finally: + pygame.display.quit() + + +@pytest.mark.parametrize("name, code, text", [ + ("p", "K_p", "p"), ("[", "K_LEFTBRACKET", "["), ("]", "K_RIGHTBRACKET", "]"), + ("up", "K_UP", ""), ("down", "K_DOWN", ""), ("return", "K_RETURN", "\r"), + ("escape", "K_ESCAPE", "\x1b"), ("space", "K_SPACE", " "), +]) +def test_key_events_name_pygames_keys(name, code, text): + pygame.display.init() + try: + down, up = TouchKeys.keyEvents(TouchKey("x", name), pygame) + finally: + pygame.display.quit() + assert down.key == getattr(pygame, code) == up.key + assert down.unicode == text + + +def test_the_2d_layout_is_the_3d_layout_scaled(): + keys = TouchKeys(OPHIDIAN) + css = keys.layout(390, 844) + scale = 0.5 # a canvas drawn at half size: twice the pixels + canvas = keys.layout(780, 1688, scale) + assert [s.label for s in css] == [s.label for s in canvas] + for a, b in zip(css, canvas): + assert (b.x * scale, b.y * scale, b.width * scale, b.height * scale) == pytest.approx( + (a.x, a.y, a.width, a.height)) + assert keys.bandHeight(780, 1688, scale) == keys.bandHeight(390, 844) / scale + # the same hit test, in each surface's pixels + a = css[2] + assert keys.slotAt((a.x + 1, a.y + 1), 390, 844).label == "Retry" + assert keys.slotAt(((a.x + 1) / scale, (a.y + 1) / scale), 780, 1688, scale).label == "Retry" + + +def test_below_fits_a_2d_board_and_its_bar_to_a_phone(): + keys = TouchKeys(OPHIDIAN) + band, scale = keys.below(500, 500, 390, 844) + assert scale == pytest.approx(390 / 500.0) + assert band * scale >= MIN_TARGET + 16 + # on a landscape phone the canvas is fitted by its height, band included + band, scale = keys.below(500, 500, 844, 390) + assert (500 + band) * scale <= 390 + 1e-6 + for slot in keys.layout(500, 500 + band, scale, portrait=False): + assert slot.height * scale >= MIN_TARGET - 1e-6 + assert slot.y >= 500 + + +def test_the_2d_bar_is_drawn_with_graphik(): + surface = pygame.Surface((500, 600)) + surface.fill((255, 255, 255)) + keys = TouchKeys(OPHIDIAN) + slots = keys.draw(Graphik(surface), 500, 600, scale=390 / 500.0) + band = keys.bandHeight(500, 600, 390 / 500.0) + assert slots and surface.get_at((2, 599))[:3] == keys.barColor + slot = slots[0] + assert surface.get_at((int(slot.x) + 2, int(slot.y) + 2))[:3] == keys.color + # nothing above the band is touched + assert surface.get_at((250, int(600 - band) - 2))[:3] == (255, 255, 255) + + +def test_the_3d_bar_is_the_same_buttons_as_screen_panels_and_labels(): + keys = TouchKeys(OPHIDIAN) + labels, panels = keys.overlay(390, 844) + slots = keys.layout(390, 844) + band = keys.bandHeight(390, 844) + assert (panels[0].x, panels[0].y, panels[0].width, panels[0].height) == (0, 844 - band, 390, band) + assert [(p.x, p.y, p.width, p.height) for p in panels[1:]] == [ + (s.x, s.y, s.width, s.height) for s in slots] + assert [l.text for l in labels] == [s.label for s in slots] + # the buttons' hit test is the slots' + for button, slot in zip(keys.buttons(390, 844), slots): + assert button.rect() == (slot.x, slot.y, slot.width, slot.height) + + +def test_no_keys_no_bar(): + keys = TouchKeys() + assert keys.layout(390, 844) == [] and keys.bandHeight(390, 844) == 0 + assert keys.overlay(390, 844) == ([], []) + assert keys.press((10, 830), 390, 844) is None + + +# -- the page says whether it is a touch screen + + +def pageWith(monkeypatch, toggle): + monkeypatch.setattr(sys, "platform", "emscripten") + fake = types.ModuleType("platform") + fake.window = types.SimpleNamespace(Graphik3D=toggle) + monkeypatch.setitem(sys.modules, "platform", fake) + + +def test_the_page_says_whether_it_is_a_touch_screen(monkeypatch): + class Toggle: + value = "1" + + def touch(self): + return self.value + + toggle = Toggle() + pageWith(monkeypatch, toggle) + assert web.touchScreen() is True + toggle.value = 0 + assert web.touchScreen() is False + + +def test_an_older_template_is_no_touch_screen(monkeypatch): + pageWith(monkeypatch, types.SimpleNamespace()) + assert web.touchScreen() is False + + +def test_outside_a_browser_touch_is_off_unless_asked_for(monkeypatch): + monkeypatch.delenv("GRAPHIK_TOUCH", raising=False) + assert web.touchScreen() is False + monkeypatch.setenv("GRAPHIK_TOUCH", "1") + assert web.touchScreen() is True + + +def test_the_template_offers_touch(): + with open(web.templatePath(), encoding="utf-8") as handle: + page = handle.read() + assert "touch: touchScreen" in page + assert '"(pointer: coarse)"' in page and '"touchstart"' in page + assert 'get("touch")' in page