#!/usr/bin/python3 -I
"""plinius-greeter: the account picker in front of Phosh.

greetd shows it (default_session, as the user greeter, in phoc) when the phone has more than one
login account, and whenever no session runs, each account with its picture and username (not
the full name). A tap on an account hands its name to root
(/run/plinius-greeter/request, read by plinius-greeter-login.service); greetd then starts that
account's Phosh, which locks itself at once. The greeter itself asks for no password: PIN or
pattern, the waiting after wrong PINs and the biometrics stay those of Phosh's lock screen.

The rest is what a phone needs before anyone logs in: the time, a dark screen after a while
without a touch, the power key turns it on and off, and held down it opens the power menu (power
off, restart) as Phosh's does. Taps vibrate as in Phosh and Stevia (feedbackd's "button-pressed").

The first start: an account without a password yet (/run/plinius-login/first-start, written by
plinius-greeter-config) gets no tiles but one question, a PIN or a password. That is what the lock
screen, Settings and every other question for the password ask from then on. A PIN is typed on
the greeter's own keypad, a password with the on-screen keyboard (Stevia, started for it). The
greeter hands it to root in its own directory (/run/plinius-greeter/password); root sets it and
logs the account in, or says why not (/run/plinius-login/password-result). This screen has no
clock: it looks as the phone will after it, with the installation's background, accent colour and
plinius-ambient's dust (the defaults of the schemas, installation_look(); the greeter's own settings
live in memory only).

After the PIN or password the first start asks three more things on pages in the same look: the
language of the system (the languages Plinius speaks, the greeter switches to it at once), the
keyboard (Stevia's layouts, those of the language first) and the time zone (those of the
language's countries first, every city of tzdata by search). All four go to root together at the
end; the language and keyboard start as Plinius Boot wrote them (/etc/locale.conf,
00-keyboard.conf), the time zone as /etc/localtime has it.

For screenshots without a phone: PLINIUS_GREETER_TEST=1 writes no request, and
PLINIUS_GREETER_USERS="name,..." with PLINIUS_GREETER_LAST=name replaces the
accounts (never use real accounts for pictures), PLINIUS_GREETER_FIRST=name shows the first start,
PLINIUS_GREETER_STEP=language, keyboard or timezone one of its pages.

SPDX-License-Identifier: MIT
"""

import dataclasses
import gettext
import json
import locale
import math
import os
import random
import re
import subprocess
import sys

sys.path.insert(0, "/usr/lib/plinius-greeter")
sys.path.insert(1, os.path.dirname(os.path.abspath(__file__)))  # next to the script in the repo
import plinius_greeter_accounts as accounts  # noqa: E402

import gi  # noqa: E402

gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
gi.require_version("Graphene", "1.0")
from gi.repository import Adw, Gdk, Gio, GLib, Graphene, Gtk, Pango  # noqa: E402

try:
    gi.require_version("AccountsService", "1.0")
    from gi.repository import AccountsService  # noqa: E402
except (ValueError, ImportError):
    AccountsService = None

# Vibration on a tap through feedbackd, as Phosh and Stevia give it (libfeedback)
try:
    gi.require_version("Lfb", "0.0")
    from gi.repository import Lfb  # noqa: E402
except (ValueError, ImportError):
    Lfb = None

REQUEST_DIR = "/run/plinius-greeter"
FIRST_START = "/run/plinius-login/first-start"
PASSWORD_RESULT = "/run/plinius-login/password-result"
KEYBOARD = "/usr/bin/phosh-osk-stevia"
# How long root may take: the check against the encryption alone takes some seconds (argon2)
PASSWORD_TIMEOUT_SECONDS = 60
PIN_DIGITS = (4, 12)
PASSWORD_LENGTH = (6, 128)
LAST_USER = "/var/lib/plinius-greeter/last-user"
ICON_DIR = "/var/lib/AccountsService/icons"
TEST = os.environ.get("PLINIUS_GREETER_TEST") == "1"
# Dark after this long without a touch; the session has this long to take over
IDLE_SECONDS = 30
START_TIMEOUT_SECONDS = 25
POWER_KEY_LONG_MS = 800
# Without the schemas (the installation's look, installation_look()): Arch blue on black
ACCENT = "#1793d1"
BACKGROUND = "#000000"
DUST_FPS = 30  # as plinius-ambient draws it

# The first start's pages after the PIN, in this order
STEPS = ("pin", "language", "keyboard", "timezone")
# The languages Plinius speaks (as Plinius Boot offers them): code, own name, LANG, the countries
# whose time zones and keyboards come first
LANGUAGES = (
    ("en", "English", "en_US.UTF-8", ("US", "GB", "IE", "CA", "AU")),
    ("de", "Deutsch", "de_DE.UTF-8", ("DE", "AT", "CH")),
    ("es", "Español", "es_ES.UTF-8", ("ES", "MX", "AR")),
    ("fr", "Français", "fr_FR.UTF-8", ("FR", "BE", "CH", "CA")),
    ("it", "Italiano", "it_IT.UTF-8", ("IT", "CH")),
    ("nl", "Nederlands", "nl_NL.UTF-8", ("NL", "BE")),
    ("pl", "Polski", "pl_PL.UTF-8", ("PL",)),
    ("pt", "Português", "pt_PT.UTF-8", ("PT", "BR")),
    ("ru", "Русский", "ru_RU.UTF-8", ("RU", "BY", "KZ")),
)
# Their names in English, translated for the line below the own name
def N_(text):
    """Marks a text for translation (xgettext -kN_) that is translated where it is shown."""
    return text


LANGUAGE_NAMES = {"en": N_("English"), "de": N_("German"), "es": N_("Spanish"), "fr": N_("French"),
                  "it": N_("Italian"), "nl": N_("Dutch"), "pl": N_("Polish"), "pt": N_("Portuguese"),
                  "ru": N_("Russian")}
LOCALE_CONF = "/etc/locale.conf"
X11_KEYBOARD = "/etc/X11/xorg.conf.d/00-keyboard.conf"
LOCALTIME = "/etc/localtime"
STEVIA_LAYOUTS = "/usr/share/phosh-osk-stevia/layouts.json"
ZONE_TAB = "/usr/share/zoneinfo/zone.tab"
ISO_COUNTRIES = "/usr/share/iso-codes/json/iso_3166-1.json"
XKB_RULES = "/usr/share/X11/xkb/rules/evdev.xml"


def make_css(look):
    accent, background = look.accent, look.background
    return f"""
:root {{
  --accent-bg-color: {accent};
  --accent-color: mix({accent}, white, 0.35);
}}
window.greeter {{
  background-color: black;
  border-radius: 0;
}}
window.greeter.first-start {{
  background-color: {background};
}}
.greeter-bg {{
  background-color: black;
}}
.installation-bg {{
  background-color: {background};
}}
.clock {{
  color: white;
  font-size: 76px;
  font-weight: 200;
  font-feature-settings: "tnum";
  letter-spacing: -1px;
}}
.date {{
  color: alpha(white, 0.78);
  font-size: 17px;
  font-weight: 500;
}}
.greeter-title {{
  color: white;
  font-size: 21px;
  font-weight: 700;
}}
.greeter-subtitle {{
  color: alpha(white, 0.62);
  font-size: 15px;
}}
button.user-tile {{
  color: white;
  background-color: alpha(white, 0.07);
  border: 1px solid alpha(white, 0.10);
  border-radius: 30px;
  padding: 20px 10px 16px 10px;
  min-width: 136px;
  min-height: 0;
  transition: background-color 180ms ease-out, opacity 250ms ease-out, border-color 180ms ease-out;
}}
button.user-tile:hover {{
  background-color: alpha(white, 0.11);
}}
button.user-tile:active {{
  background-color: alpha(white, 0.17);
}}
button.user-tile.chosen {{
  background-color: alpha({accent}, 0.28);
  border-color: alpha({accent}, 0.75);
}}
button.user-tile.dimmed {{
  opacity: 0.22;
}}
.avatar-ring {{
  border-radius: 9999px;
  padding: 4px;
  border: 3px solid alpha(white, 0.14);
}}
.last .avatar-ring {{
  border-color: {accent};
}}
.user-name {{
  font-size: 17px;
  font-weight: 700;
}}
.status {{
  color: alpha(white, 0.85);
  font-size: 15px;
}}
.status.error {{
  color: #ff9b8f;
}}
/* The power menu as Phosh's looks on the phone (phosh-plinius 0.59, measured on its screenshot):
   a grey card over the darkened screen, each entry a darker rounded field, the close button a
   circle on the card's top right corner */
.power-menu {{
  background-color: alpha(black, 0.8);
}}
.power-card {{
  color: #eeeeec;
  background-color: #353535;
  border: 1px solid alpha(white, 0.1);
  border-radius: 32px;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2);
  padding: 24px 18px 20px 18px;
}}
.power-card button.entry {{
  color: #eeeeec;
  background-color: #282828;
  border-radius: 18px;
  min-height: 59px;
  min-width: 174px;
  padding: 0;
  font-size: 11pt;
  font-weight: bold;
  box-shadow: none;
}}
.power-card button.entry:hover {{
  background-color: #2e2e2e;
}}
.power-card button.entry:active {{
  background-color: #3c3c3c;
}}
.power-card button.entry image {{
  opacity: 0.8;
}}
button.power-close {{
  color: #eeeeec;
  background-color: #282828;
  border-radius: 9999px;
  min-width: 40px;
  min-height: 40px;
  padding: 0;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2);
}}
button.power-close:active {{
  background-color: #3c3c3c;
}}
.blank {{
  background-color: black;
}}
/* The first start as Phosh's unlock page (phosh-plinius: lockscreen.ui, keypad.ui, common.css;
   the keypad's size from fit_keypad()) */
.unlock-status {{
  color: white;
  font-size: 16pt;
  text-shadow: 1px 1px 1.1px rgba(0, 0, 0, 0.6);
}}
.pin-dots {{
  color: white;
  font-size: 20px;
  padding: 6px;
  min-height: 30px;
  text-shadow: 1px 1px 1.1px rgba(0, 0, 0, 0.6);
}}
button.key {{
  color: white;
  background: none;
  border-radius: 9999px;
  padding: 0;
  font-size: 16px;
  font-weight: bold;
}}
button.key label {{
  font-weight: bold;
  text-shadow: 1px 1px 1.1px rgba(0, 0, 0, 0.6);
}}
button.key image {{
  -gtk-icon-shadow: 1px 1px 1.1px rgba(0, 0, 0, 0.6);
}}
/* Only while pressed: with touch GTK 4 keeps :hover and the focus on the last key */
button.key:active {{
  background: alpha(white, 0.3);
}}
button.pin-submit {{
  color: white;
  font-size: 16px;
  font-weight: bold;
  padding: 16px 36px;
  border-radius: 9999px;
  background-color: alpha(white, 0.3);
}}
button.pin-submit:not(:disabled) {{
  background-color: {accent};
}}
button.pin-mode {{
  color: white;
  background-color: alpha(white, 0.15);
  border-radius: 9999px;
  min-width: 52px;
  min-height: 52px;
  padding: 0;
}}
/* The pages after the PIN: where the first start is, a list as a card over the background */
.step-dot {{
  background-color: alpha(white, 0.3);
  border-radius: 9999px;
  min-width: 8px;
  min-height: 8px;
  transition: min-width 200ms ease-out, background-color 200ms ease-out;
}}
.step-dot.current {{
  background-color: {accent};
  min-width: 24px;
}}
.step-dot.done {{
  background-color: alpha(white, 0.75);
}}
list.setup-list {{
  color: white;
  background-color: alpha(black, 0.35);
  border: 1px solid alpha(white, 0.12);
  border-radius: 24px;
}}
list.setup-list > row {{
  padding: 9px 20px;
  min-height: 34px;
  border-bottom: 1px solid alpha(white, 0.08);
}}
list.setup-list > row:last-child {{
  border-bottom: none;
}}
list.setup-list > row:active {{
  background-color: alpha(white, 0.12);
}}
.setup-row-title {{
  font-size: 16px;
}}
.setup-row-subtitle {{
  color: alpha(white, 0.6);
  font-size: 13px;
}}
.setup-row-time {{
  color: alpha(white, 0.75);
  font-size: 15px;
  font-feature-settings: "tnum";
}}
row.chosen .setup-row-title {{
  font-weight: 700;
}}
.setup-check {{
  color: {accent};
}}
.setup-section {{
  color: alpha(white, 0.6);
  font-size: 13px;
  font-weight: 700;
  margin: 14px 20px 6px 20px;
}}
entry.setup-search, entry.setup-try {{
  color: white;
  background-color: alpha(black, 0.35);
  border: 1px solid alpha(white, 0.12);
  border-radius: 9999px;
  min-height: 44px;
  padding: 0 16px;
}}
"""


# Phosh's keypad (phosh-plinius 0012): at most this share of the screen's height and its width
# less the side margins, three columns and four rows 6 px apart, buttons of 80 to 120 px with the
# digit growing along (32 px at 80); KEYPAD_EXTRA the status, the PIN and the unlock button
KEYPAD_SIDE_MARGIN = 24
KEYPAD_HEIGHT_SHARE = 0.55
KEYPAD_BUTTON = (80, 120)
KEYPAD_SPACING = 6
KEYPAD_EXTRA = 150


# A key takes no focus (no key stays marked) and keeps its own square in its cell of the grid, whose
# rows can be taller: a round highlight, not an oval one
KEY_PROPS = {"css_classes": ["key"], "focusable": False, "focus_on_click": False,
             "halign": Gtk.Align.CENTER, "valign": Gtk.Align.CENTER}
# The column's margin at the top: room for the clock, less on the first start, where the keypad as
# big as on the lock screen needs it
COLUMN_TOP = 64
COLUMN_TOP_FIRST = 32
# The pages after the PIN: below the dots that say where the first start is
COLUMN_TOP_SETUP = 56


def keypad_button_size(width, height):
    """The size of a keypad button on a screen of width x height, as Phosh's lock screen has it."""
    room_width = width - 2 * KEYPAD_SIDE_MARGIN
    room_height = height * KEYPAD_HEIGHT_SHARE
    button = min((room_width - 2 * KEYPAD_SPACING) // 3, int((room_height - KEYPAD_EXTRA - 3 * KEYPAD_SPACING) // 4))
    return min(max(button, KEYPAD_BUTTON[0]), KEYPAD_BUTTON[1])


def keypad_css(button):
    return (f"button.key {{ min-width: {button}px; min-height: {button}px; }}\n"
            f"button.key label {{ font-size: {32 * button // KEYPAD_BUTTON[0]}px; }}\n")


@dataclasses.dataclass
class Look:
    """The installation's look: background colour, the picture over it (or None), accent colour,
    plinius-ambient's effect and its density."""
    background: str = BACKGROUND
    picture: str = None
    accent: str = ACCENT
    effect: str = "dust"
    density: str = "medium"


def installation_look(source=None):
    """The look a new account starts with: the schemas' defaults with the installation's overrides
    (device-volla-ansuz's 90-plinius.gschema.override, the Phosh sections for XDG_CURRENT_DESKTOP),
    never an account's own settings. Anything missing or unusable keeps the value of Look()."""
    if source is None:
        source = Gio.SettingsSchemaSource.get_default()

    def default(schema_id, key):
        schema = source.lookup(schema_id, True) if source is not None else None
        if schema is None or not schema.has_key(key):
            return None
        return schema.get_key(key).get_default_value().unpack()

    def color(value):
        # Only #rgb and #rrggbb: the value goes into the CSS
        return value if isinstance(value, str) and re.fullmatch(r"#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})", value) else None

    look = Look()
    # Phosh's custom accent (phosh-plinius), else GNOME's own colour has no hex value to use
    look.accent = color(default("org.plinius.appearance", "accent-color")) or look.accent
    look.background = color(default("org.gnome.desktop.background", "primary-color")) or look.background
    if (default("org.gnome.desktop.background", "picture-options") or "none") != "none":
        # The greeter is always dark
        for key in ("picture-uri-dark", "picture-uri"):
            uri = default("org.gnome.desktop.background", key)
            path = Gio.File.new_for_uri(uri).get_path() if uri else None
            if path and os.path.isfile(path):
                look.picture = path
                break
    look.effect = default("org.plinius.ambient", "effect") or "none"
    density = default("org.plinius.ambient", "density")
    if density in DustField.COUNTS:
        look.density = density
    return look


# ----- plinius-ambient's dust, for the first start -----

def smoothstep(e0, e1, x):
    t = min(max((x - e0) / (e1 - e0), 0.0), 1.0)
    return t * t * (3 - 2 * t)


class DustField:
    """plinius-ambient's dust (effects.c, dust_*) with its numbers: motes drifting in a beam of
    light from the upper left, a few big ones out of focus in front of the lens. Sizes in logical
    pixels of a screen width by height; sprites() says what to draw."""

    COUNTS = {"low": 70, "medium": 140, "high": 240}
    FOCUS_DEPTH = 0.45
    FOREGROUND_MAX = 1.7
    FOREGROUND_SHARE = 0.07
    BEAM_DIR = (0.42, 0.91)
    SHARPNESS_LEVELS = 4  # the sharp motes' glow comes in this many textures (glow_pixels)

    def __init__(self, width, height, density="medium", rng=None):
        self.rng = rng or random.Random()
        self.width, self.height = width, height
        self.time = 0.0
        area = width * height / (360.0 * 800.0)
        self.motes = [self.make_mote() for _ in range(max(1, int(self.COUNTS[density] * min(max(area, 0.25), 4.0))))]

    def unit(self):
        w = min(self.width, self.height)
        return w / 360.0 if w > 0 else 1.0

    def random_depth(self):
        if self.rng.random() < self.FOREGROUND_SHARE:
            return self.rng.uniform(1.0, self.FOREGROUND_MAX)
        z = self.rng.random()
        return z * z  # more far motes than near ones

    def blur_of(self, z):
        return min(max((z - self.FOCUS_DEPTH) / (self.FOREGROUND_MAX - self.FOCUS_DEPTH) * 1.4, 0.0), 1.0)

    def make_mote(self):
        z = self.random_depth()
        size = (0.8 + 2.2 * z if z <= 1 else 5 + 9 * (z - 1) / (self.FOREGROUND_MAX - 1)) * self.unit()
        return {"x": self.rng.random() * self.width, "y": self.rng.random() * self.height, "vx": 0.0, "vy": 0.0,
                "z": z, "size": size, "phase": self.rng.random() * 2 * math.pi, "freq": self.rng.uniform(0.6, 2.0)}

    def resize(self, width, height):
        sx = width / self.width if self.width else 1.0
        sy = height / self.height if self.height else 1.0
        for m in self.motes:
            m["x"] *= sx
            m["y"] *= sy
        self.width, self.height = width, height

    def step(self, dt):
        """Brownian drift with a little warm air rising, damped so it stays a float; nearer motes
        seem to move faster (parallax)."""
        u = self.unit()
        self.time += dt
        damp = math.exp(-0.8 * dt)
        for m in self.motes:
            near = 0.5 + m["z"]
            m["vx"] = (m["vx"] + self.rng.uniform(-1, 1) * 18 * near * u * dt) * damp
            m["vy"] = (m["vy"] + (self.rng.uniform(-1, 1) * 18 - 1.5) * near * u * dt) * damp
            m["x"] = (m["x"] + (m["vx"] + 2 * near * u) * dt) % self.width
            m["y"] = (m["y"] + m["vy"] * dt) % self.height

    def beam_distance(self, x, y):
        dx, dy = self.BEAM_DIR
        return abs((x - 0.2 * self.width) * dy - y * dx)

    def beam(self):
        """(centre x, centre y, half width, half length, angle in degrees, opacity): the beam's
        texture (top row at its source) turned around its centre."""
        dx, dy = self.BEAM_DIR
        length = math.hypot(self.width, self.height)
        breathe = 0.85 + 0.15 * math.sin(self.time * 0.25)
        angle = math.atan2(dx, -dy) + math.pi
        return (0.2 * self.width + dx * length * 0.5, dy * length * 0.5, 0.32 * self.width, length * 0.55,
                math.degrees(angle), 0.17 * breathe)

    def sprites(self):
        """(kind, centre x, centre y, half size, opacity) per mote; kind "bokeh" or the level of
        sharpness 0 (sharp) .. SHARPNESS_LEVELS - 1."""
        beam_half = 0.32 * self.width
        result = []
        for m in self.motes:
            # Lit inside the beam, barely visible outside of it
            lit = 0.18 + 0.82 * min(max(1.2 - self.beam_distance(m["x"], m["y"]) / beam_half, 0.0), 1.0)
            b = lit * (0.55 + 0.45 * math.sin(self.time * m["freq"] + m["phase"]))
            if m["z"] > 1:
                # In front of the lens: a faint disc of light
                result.append(("bokeh", m["x"], m["y"], m["size"], 0.3 * b))
            else:
                level = round(self.blur_of(m["z"]) * (self.SHARPNESS_LEVELS - 1))
                result.append((level, m["x"], m["y"], m["size"] * 3, b))
        return result


MOTE_COLOR = (1.0, 0.93, 0.78)
BEAM_COLOR = (1.0, 0.853, 0.588)  # plinius-ambient's (0.17, 0.145, 0.10) at full strength


def glow_pixels(kind, size):
    """RGBA, premultiplied, of a size x size sprite of kind "bokeh", "beam" (size wide, 4 x size
    high, the source at the top) or a sharpness level (DustField.sprites()); the profiles of
    plinius-ambient's glow shader."""
    height = size * 4 if kind == "beam" else size
    color = BEAM_COLOR if kind == "beam" else MOTE_COLOR
    if isinstance(kind, int):
        q = 0.6 - 0.5 * kind / (DustField.SHARPNESS_LEVELS - 1)
    out = bytearray(size * height * 4)
    for row in range(height):
        v = 1 - 2 * (row + 0.5) / height
        for col in range(size):
            u = 2 * (col + 0.5) / size - 1
            r2 = u * u + v * v
            if kind == "beam":
                a = math.exp(-u * u * 2.2) * (1 - u * u) * smoothstep(-1.0, 0.2, v)
            elif r2 > 1:
                continue
            elif kind == "bokeh":
                r = math.sqrt(r2)
                a = smoothstep(1.0, 0.86, r) * (0.6 + 0.4 * smoothstep(0.45, 0.95, r))
            else:
                a = (math.exp(-r2 * (6 + 54 * q)) + math.exp(-r2 * 5) * 0.25) * (1 - r2)
            a = min(max(a, 0.0), 1.0)
            i = (row * size + col) * 4
            out[i:i + 4] = bytes((round(color[0] * a * 255), round(color[1] * a * 255), round(color[2] * a * 255),
                                  round(a * 255)))
    return bytes(out)


class DustArea(Gtk.Widget):
    """Draws a DustField over the background at DUST_FPS frames a second while running."""

    def __init__(self, density="medium"):
        super().__init__(can_target=False, hexpand=True, vexpand=True)
        self.density = density
        self.field = None
        self.textures = None
        self.tick = 0
        self.last = None

    def set_running(self, running):
        if running and not self.tick:
            self.last = None
            self.tick = self.add_tick_callback(self.on_tick)
        elif not running and self.tick:
            self.remove_tick_callback(self.tick)
            self.tick = 0

    def on_tick(self, _widget, clock):
        now = clock.get_frame_time() / 1e6
        if self.last is None:
            self.last = now
        elif now - self.last >= 1 / DUST_FPS - 0.004:
            if self.field is not None:
                self.field.step(min(now - self.last, 0.1))
            self.last = now
            self.queue_draw()
        return GLib.SOURCE_CONTINUE

    @staticmethod
    def texture(kind, size):
        height = size * 4 if kind == "beam" else size
        return Gdk.MemoryTexture.new(size, height, Gdk.MemoryFormat.R8G8B8A8_PREMULTIPLIED,
                                     GLib.Bytes.new(glow_pixels(kind, size)), size * 4)

    def do_snapshot(self, snapshot):
        width, height = self.get_width(), self.get_height()
        if width <= 0 or height <= 0:
            return
        if self.field is None:
            self.field = DustField(width, height, self.density)
        elif (width, height) != (self.field.width, self.field.height):
            self.field.resize(width, height)
        if self.textures is None:
            self.textures = {"beam": self.texture("beam", 48), "bokeh": self.texture("bokeh", 128)}
            for level in range(DustField.SHARPNESS_LEVELS):
                self.textures[level] = self.texture(level, 64)
        cx, cy, half_w, half_l, angle, opacity = self.field.beam()
        snapshot.save()
        snapshot.translate(Graphene.Point().init(cx, cy))
        snapshot.rotate(angle)
        snapshot.push_opacity(opacity)
        snapshot.append_texture(self.textures["beam"], Graphene.Rect().init(-half_w, -half_l, 2 * half_w, 2 * half_l))
        snapshot.pop()
        snapshot.restore()
        for kind, x, y, half, opacity in self.field.sprites():
            if opacity <= 0.004:
                continue
            snapshot.push_opacity(min(opacity, 1.0))
            snapshot.append_texture(self.textures[kind], Graphene.Rect().init(x - half, y - half, 2 * half, 2 * half))
            snapshot.pop()


def setup_feedback():
    """Connects libfeedback to feedbackd (started on the greeter's session bus when first asked);
    without it the greeter works the same, only without vibration."""
    if Lfb is None:
        return
    try:
        Lfb.init("org.plinius.Greeter")
    except GLib.Error as e:
        print(f"plinius-greeter: feedback: {e.message}", file=sys.stderr)


def feedback(event="button-pressed"):
    """A short vibration from feedbackd's theme for the event: "button-pressed" is a tap."""
    if Lfb is None or not Lfb.is_initted():
        return

    def done(ev, result):
        try:
            ev.trigger_feedback_finish(result)
        except GLib.Error as e:
            print(f"plinius-greeter: feedback: {e.message}", file=sys.stderr)
    Lfb.Event.new(event).trigger_feedback_async(None, done)


def setup_locale():
    """greetd starts the greeter without LANG: take the system's (as the other screens before login)."""
    if not os.environ.get("LANG"):
        try:
            with open("/etc/locale.conf", encoding="utf-8") as f:
                for line in f:
                    key, _, value = line.strip().partition("=")
                    if key.startswith("LANG") or key.startswith("LC_"):
                        os.environ.setdefault(key, value.strip().strip('"'))
        except OSError:
            pass
    try:
        locale.setlocale(locale.LC_ALL, "")
    except locale.Error:
        locale.setlocale(locale.LC_ALL, "C.UTF-8")
    gettext.bindtextdomain("plinius-greeter", "/usr/share/locale")
    gettext.textdomain("plinius-greeter")


_ = gettext.gettext


class Account:
    """An account as the greeter shows it: its picture and its username, never the full name."""

    def __init__(self, name, icon=None):
        self.name = name
        self.icon = icon


def read_last_user():
    if TEST:
        return os.environ.get("PLINIUS_GREETER_LAST", "")
    try:
        with open(LAST_USER, encoding="utf-8") as f:
            return f.read().strip()
    except OSError:
        return ""


def base_accounts():
    if TEST and os.environ.get("PLINIUS_GREETER_USERS"):
        result = []
        for item in os.environ["PLINIUS_GREETER_USERS"].split(","):
            result.append(Account(item.partition(":")[0].strip()))
        return result
    result = []
    for entry in accounts.login_users():
        icon = os.path.join(ICON_DIR, entry.pw_name)
        result.append(Account(entry.pw_name, icon if os.path.isfile(icon) else None))
    return result


def ordered(account_list, last):
    """The account used last first, the others by name."""
    rest = sorted((a for a in account_list if a.name != last), key=lambda a: a.name)
    first = [a for a in account_list if a.name == last]
    return first + rest


def read_first_start():
    """The account that has no password yet, or ""."""
    if TEST:
        return os.environ.get("PLINIUS_GREETER_FIRST", "")
    try:
        with open(FIRST_START, encoding="utf-8") as f:
            return f.read(256).strip()
    except OSError:
        return ""


def secret_problem(kind, secret, again):
    """Why the first PIN or password cannot be used, or "" (root checks the same, plinius-greeter-config)."""
    if kind == "pin":
        if not secret.isascii() or not secret.isdigit() or not PIN_DIGITS[0] <= len(secret) <= PIN_DIGITS[1]:
            return _("A PIN has 4 to 12 digits.")
        if secret != again:
            return _("The PINs do not match. Please enter it again.")
        return ""
    if not PASSWORD_LENGTH[0] <= len(secret) <= PASSWORD_LENGTH[1] or any(ord(c) < 0x20 or ord(c) == 0x7F
                                                                         for c in secret):
        return _("A password has at least 6 characters.")
    if secret.isascii() and secret.isdigit():
        return _("A password of digits only is a PIN: choose PIN above.")
    if secret != again:
        return _("The passwords do not match. Please enter them again.")
    return ""


def time_format():
    try:
        t_fmt = locale.nl_langinfo(locale.T_FMT)
    except (AttributeError, ValueError):
        t_fmt = "%H:%M:%S"
    return "%-l:%M" if ("%p" in t_fmt or "%I" in t_fmt or "%r" in t_fmt) else "%H:%M"


# ----- language, keyboard and time zone of the first start -----

def read_key_values(path):
    """KEY=value lines of a file such as locale.conf, {} if there is none."""
    result = {}
    try:
        with open(path, encoding="utf-8") as f:
            for line in f:
                key, sep, value = line.strip().partition("=")
                if sep and not key.startswith("#"):
                    result[key.strip()] = value.strip().strip('"')
    except OSError:
        pass
    return result


def read_language(path=None):
    """The code of the system's language among LANGUAGES (as Plinius Boot set it), else "en"."""
    path = path or LOCALE_CONF
    lang = read_key_values(path).get("LANG", "")
    code = lang.split(".")[0].split("_")[0]
    return code if any(entry[0] == code for entry in LANGUAGES) else "en"


def read_keyboard(path=None):
    """The system's first keyboard layout as Stevia names it ("de", "ch+fr"), else "us"."""
    path = path or X11_KEYBOARD
    options = {}
    try:
        with open(path, encoding="utf-8") as f:
            for line in f:
                match = re.match(r'\s*Option\s+"(Xkb\w+)"\s+"([^"]*)"', line)
                if match:
                    options[match.group(1)] = match.group(2)
    except OSError:
        pass
    layout = options.get("XkbLayout", "").split(",")[0].strip()
    variant = options.get("XkbVariant", "").split(",")[0].strip()
    if not re.fullmatch(r"[a-z]{2,8}", layout):
        return "us"
    return f"{layout}+{variant}" if re.fullmatch(r"[A-Za-z0-9_-]+", variant) else layout


def read_timezone(path=None):
    """The system's time zone ("Europe/Berlin") from the link /etc/localtime, else "UTC"."""
    path = path or LOCALTIME
    try:
        target = os.readlink(path)
    except OSError:
        return "UTC"
    _before, sep, zone = target.partition("zoneinfo/")
    return zone if sep and zone else "UTC"


def stevia_layouts(path=None):
    """[(layout id, language, English name)] of the layouts the on-screen keyboard has."""
    path = path or STEVIA_LAYOUTS
    try:
        with open(path, encoding="utf-8") as f:
            data = json.load(f)
    except (OSError, ValueError):
        return [("us", "en", "English (US)")]
    return [(item["layout-id"], item.get("language", ""), item.get("name", item["layout-id"]))
            for item in data.get("layouts", []) if item.get("type") == "xkb" and item.get("layout-id")]


def xkb_descriptions(path=None):
    """{layout id ("de", "ch+fr"): English description} of xkeyboard-config, whose domain
    xkeyboard-config translates them; {} without it."""
    path = path or XKB_RULES
    import xml.etree.ElementTree as ElementTree
    try:
        root = ElementTree.parse(path).getroot()
    except (OSError, ElementTree.ParseError):
        return {}
    result = {}
    for layout in root.iterfind("layoutList/layout"):
        name = layout.findtext("configItem/name")
        result[name] = layout.findtext("configItem/description") or name
        for variant in layout.iterfind("variantList/variant"):
            result[f"{name}+{variant.findtext('configItem/name')}"] = variant.findtext("configItem/description")
    return result


def stevia_layouts_named(path=None, rules=None):
    """stevia_layouts() with xkeyboard-config's names where it has them (those are translated)."""
    names = xkb_descriptions(rules)
    return [(layout, language, names.get(layout) or name) for layout, language, name in stevia_layouts(path)]


def keyboard_choices(code, layouts, chosen):
    """(suggested, others) of the layouts: those of the language first (its own layout at the top,
    the chosen one always among them, US English last), the others by name."""
    def own(language):
        return language == code or language.startswith(code + "-")
    suggested = [item for item in layouts if own(item[1])]
    suggested.sort(key=lambda item: (item[0] != code, item[2]))
    for wanted in (chosen, "us"):
        item = next((i for i in layouts if i[0] == wanted), None)
        if item is None or item in suggested:
            continue
        if wanted == "us":
            suggested.append(item)
        else:
            suggested.insert(0, item)
    others = sorted((item for item in layouts if item not in suggested), key=lambda item: item[2])
    return suggested, others


def read_zones(path=None):
    """[(country code, time zone)] in zone.tab's order: a country's main zone comes first."""
    path = path or ZONE_TAB
    result = []
    try:
        with open(path, encoding="utf-8") as f:
            for line in f:
                fields = line.split("\t")
                if len(fields) >= 3 and not line.startswith("#"):
                    result.append((fields[0], fields[2].strip()))
    except OSError:
        pass
    return result


def read_countries(path=None):
    """{country code: name} in English (iso-codes); translated with the domain iso_3166-1."""
    path = path or ISO_COUNTRIES
    try:
        with open(path, encoding="utf-8") as f:
            data = json.load(f)
    except (OSError, ValueError):
        return {}
    return {c["alpha_2"]: c.get("common_name", c["name"]) for c in data.get("3166-1", []) if "alpha_2" in c}


def city_of(zone):
    """The city of a time zone in the language shown now ("Europe/Vienna": "Wien" in German), with
    the names of libgweather's locations (gweather-locations), else tzdata's English one."""
    city = zone.rsplit("/", 1)[-1].replace("_", " ")
    return gettext.dgettext("gweather-locations", city)


def timezone_choices(code, zones, chosen):
    """The suggested time zones: the chosen one, then the main zone of each country of the language."""
    countries = next((entry[3] for entry in LANGUAGES if entry[0] == code), ())
    result = [chosen] if chosen != "UTC" else []
    for country in countries:
        zone = next((z for c, z in zones if c == country), None)
        if zone and zone not in result:
            result.append(zone)
    return result


def zone_time(zone, time_fmt):
    """("UTC+01:00", "14:32") for a time zone now."""
    tz = GLib.TimeZone.new_identifier(zone) or GLib.TimeZone.new_utc()
    now = GLib.DateTime.new_now(tz)
    offset = now.get_utc_offset() // 60_000_000
    sign = "+" if offset >= 0 else "−"
    return f"UTC{sign}{abs(offset) // 60:02d}:{abs(offset) % 60:02d}", now.format(time_fmt).strip()


def set_ui_language(code):
    """The greeter's own texts from now on in this language (gettext reads LANGUAGE at each call)."""
    os.environ["LANGUAGE"] = code


class Greeter(Adw.ApplicationWindow):
    def __init__(self, app, look=None):
        super().__init__(application=app, title="Plinius")
        self.add_css_class("greeter")
        self.look = look or installation_look()
        self.accounts = []
        self.last = read_last_user()
        self.tiles = {}
        self.choosing = None
        self.failed = False
        self.start_timeout = 0
        self.idle_timeout = 0
        self.blanked = False
        self.saved_brightness = None
        self.power_key_timeout = 0
        self.power_key_long = False
        self.time_format = time_format()
        # The first start (see the module's text): the account, PIN or password, the PIN typed so far
        # and the first of its two entries
        self.first = read_first_start()
        self.kind = "pin"
        self.digits = ""
        self.first_pin = None
        self.result_before = None
        self.password_timeout = 0
        self.keyboard = None
        # The pages after the PIN: where the first start is, the PIN or password waiting for the end,
        # what is chosen (the system's settings at first) and the lists, read when first shown
        self.step = "pin"
        self.pending_secret = None
        self.choice = {"language": read_language(), "keyboard": read_keyboard(), "timezone": read_timezone()}
        self.layouts = None
        self.zones = read_zones()
        self.countries = None
        # Without a time zone yet (UTC) the main one of the language's first country
        if self.choice["timezone"] == "UTC":
            self.choice["timezone"] = (timezone_choices(self.choice["language"], self.zones, "UTC") or ["UTC"])[0]
        # The pages chosen on by hand: a new language changes the others only where not
        self.touched = set()

        overlay = Gtk.Overlay()
        background = Gtk.Box()
        background.add_css_class("greeter-bg")
        overlay.set_child(background)
        # The first start: the installation's background and dust instead of the greeter's own
        self.installation_bg = Gtk.Box(css_classes=["installation-bg"], can_target=False)
        if self.look.picture:
            self.installation_bg.append(Gtk.Picture(file=Gio.File.new_for_path(self.look.picture), hexpand=True,
                                                    vexpand=True, content_fit=Gtk.ContentFit.COVER))
        overlay.add_overlay(self.installation_bg)
        self.dust = DustArea(self.look.density) if self.look.effect == "dust" else None
        if self.dust is not None:
            overlay.add_overlay(self.dust)

        column = self.column = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        column.set_margin_start(24)
        column.set_margin_end(24)
        column.set_margin_top(COLUMN_TOP)
        column.set_margin_bottom(40)
        overlay.add_overlay(column)
        # The keypad grows with the screen (fit_keypad): a widget that only says the size
        self.keypad_css = None
        sizer = Gtk.DrawingArea(can_target=False, hexpand=True, vexpand=True)
        sizer.connect("resize", lambda _a, width, height: self.fit_keypad(width, height))
        overlay.add_overlay(sizer)

        self.clock = Gtk.Label(css_classes=["clock"])
        self.date = Gtk.Label(css_classes=["date"])
        column.append(self.clock)
        column.append(self.date)

        self.spacers = [Gtk.Box(vexpand=True), Gtk.Box(vexpand=True)]
        column.append(self.spacers[0])

        self.title = Gtk.Label(label=_("Who is using the phone?"), css_classes=["greeter-title"],
                               wrap=True, justify=Gtk.Justification.CENTER)
        self.subtitle = Gtk.Label(label=_("Tap your account, then unlock it as usual."),
                                  css_classes=["greeter-subtitle"], wrap=True, justify=Gtk.Justification.CENTER)
        self.subtitle.set_margin_top(6)
        self.subtitle.set_margin_bottom(24)
        column.append(self.title)
        column.append(self.subtitle)

        # Rows of two tiles; a single one in the last row stays in the middle
        self.rows = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=16, halign=Gtk.Align.CENTER)
        scroller = self.rows_scroller = Gtk.ScrolledWindow(hscrollbar_policy=Gtk.PolicyType.NEVER,
                                                           propagate_natural_height=True, max_content_height=560,
                                                           child=self.rows)
        column.append(scroller)
        self.first_box = self.make_first_start()
        column.append(self.first_box)

        self.status = Gtk.Box(spacing=10, halign=Gtk.Align.CENTER)
        self.status.set_margin_top(22)
        self.spinner = Adw.Spinner(width_request=20, height_request=20)
        self.status_label = Gtk.Label(css_classes=["status"], wrap=True, justify=Gtk.Justification.CENTER)
        self.status.append(self.spinner)
        self.status.append(self.status_label)
        self.status.set_opacity(0)
        column.append(self.status)

        column.append(self.spacers[1])

        # Where the first start is: a dot per page, the current one long in the accent colour
        self.step_dots = Gtk.Box(spacing=8, halign=Gtk.Align.CENTER, valign=Gtk.Align.START, can_target=False)
        self.step_dots.set_margin_top(18)
        self.dots_of_steps = [Gtk.Box(css_classes=["step-dot"], valign=Gtk.Align.CENTER) for _step in STEPS]
        for dot in self.dots_of_steps:
            self.step_dots.append(dot)
        overlay.add_overlay(self.step_dots)

        self.power_menu = self.make_power_menu()
        overlay.add_overlay(self.power_menu)

        self.blank = Gtk.Box(css_classes=["blank"], visible=False, can_target=True)
        tap = Gtk.GestureClick()
        tap.connect("released", lambda *_a: self.wake())
        self.blank.add_controller(tap)
        overlay.add_overlay(self.blank)

        self.set_content(overlay)

        anything = Gtk.EventControllerLegacy()
        anything.connect("event", self.on_any_event)
        self.add_controller(anything)
        keys = Gtk.EventControllerKey(propagation_phase=Gtk.PropagationPhase.CAPTURE)
        keys.connect("key-pressed", self.on_key_pressed)
        keys.connect("key-released", self.on_key_released)
        self.add_controller(keys)

        self.update_clock()
        GLib.timeout_add_seconds(1, self.update_clock)
        self.show_mode()
        self.load_accounts()
        self.restart_idle()
        if TEST and self.first and os.environ.get("PLINIUS_GREETER_STEP") in STEPS:
            self.pending_secret = "0000"
            self.go_to(os.environ["PLINIUS_GREETER_STEP"], animate=False)

    def show_mode(self):
        """The first start in the installation's look without a clock, else the account picker."""
        first = bool(self.first)
        if first:
            self.add_css_class("first-start")
        else:
            self.remove_css_class("first-start")
        self.clock.set_visible(not first)
        self.date.set_visible(not first)
        self.column.set_margin_top(COLUMN_TOP_FIRST if first else COLUMN_TOP)
        self.subtitle.set_margin_bottom(12 if first else 24)
        self.first_box.set_visible(first)
        self.step_dots.set_visible(first)
        self.mark_step()
        self.installation_bg.set_visible(first)
        if self.dust is not None:
            self.dust.set_visible(first)
            self.dust.set_running(first and not self.blanked)

    # ----- accounts -----

    def load_accounts(self):
        self.accounts = base_accounts()
        self.fill()
        if AccountsService is None or TEST:
            return
        # AccountsService knows the pictures and the locked accounts; it can come late or not at all
        manager = AccountsService.UserManager.get_default()
        if manager.props.is_loaded:
            self.from_accounts_service(manager)
        else:
            manager.connect("notify::is-loaded", lambda m, _p: self.from_accounts_service(m))

    def from_accounts_service(self, manager):
        if not manager.props.is_loaded or manager.no_service():
            return
        known = {u.get_user_name(): u for u in manager.list_users()}
        result = []
        for account in self.accounts:
            user = known.get(account.name)
            if user is not None and user.is_loaded():
                if user.get_locked():
                    continue
                icon = user.get_icon_file()
                if icon and os.path.isfile(icon):
                    account.icon = icon
            result.append(account)
        self.accounts = result
        self.fill()

    def fill(self):
        if self.choosing:
            return
        if self.first:
            # One question instead of the accounts: nothing to pick, nothing logged in by itself
            self.title.set_label(_("Protect your phone"))
            self.subtitle.set_label(_("Choose how to unlock it. Settings and every other question for the password "
                                      "ask for the same."))
            return
        while (child := self.rows.get_first_child()) is not None:
            self.rows.remove(child)
        self.tiles = {}
        account_list = ordered(self.accounts, self.last)
        # A single account to offer (the others locked) is no choice: log it in without showing it.
        # Only once: after a failed start its tile shows, to try again by hand.
        single = len(account_list) == 1 and not self.failed
        self.title.set_visible(not single)
        self.subtitle.set_visible(not single)
        if single:
            GLib.idle_add(self.choose, account_list[0])
            return
        row = None
        for i, account in enumerate(account_list):
            if i % 2 == 0:
                row = Gtk.Box(spacing=16, halign=Gtk.Align.CENTER, homogeneous=True)
                self.rows.append(row)
            tile = self.make_tile(account, account.name == self.last and len(account_list) > 1)
            self.tiles[account.name] = tile
            row.append(tile)

    def make_tile(self, account, last):
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        ring = Gtk.Box(halign=Gtk.Align.CENTER, css_classes=["avatar-ring"])
        avatar = Adw.Avatar(size=88, text=account.name, show_initials=True)
        if account.icon:
            try:
                avatar.set_custom_image(Gdk.Texture.new_from_filename(account.icon))
            except GLib.Error:
                pass
        ring.append(avatar)
        box.append(ring)
        name = Gtk.Label(label=account.name, css_classes=["user-name"], ellipsize=Pango.EllipsizeMode.END,
                         max_width_chars=12)
        box.append(name)

        button = Gtk.Button(child=box, css_classes=["user-tile"], width_request=156)
        if last:
            button.add_css_class("last")
        button.update_property([Gtk.AccessibleProperty.LABEL], [account.name])
        button.connect("clicked", lambda _b: (feedback(), self.choose(account)))
        return button

    # ----- the first start -----

    def make_first_start(self):
        """The question of the first start laid out as Phosh's unlock page: the status, the PIN, the
        keypad with the keyboard bottom left and delete bottom right, the button below it."""
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12, halign=Gtk.Align.CENTER)
        self.first_prompt = Gtk.Label(css_classes=["unlock-status"], wrap=True, justify=Gtk.Justification.CENTER)
        box.append(self.first_prompt)

        # The PIN: dots, the keypad and the button to go on
        self.pin_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12, halign=Gtk.Align.CENTER)
        self.dots = Gtk.Label(css_classes=["pin-dots"])
        self.dots.set_margin_top(12)
        self.dots.set_margin_bottom(12)
        self.pin_box.append(self.dots)
        # Rows exactly as tall as the keys, as on the lock screen: GTK 4 aligns the baselines of labels in
        # a row of the grid (homogeneous ones even more), which makes rows taller than their keys. Each
        # key sits in a box of its own, which gives no baseline.
        keypad = Gtk.Grid(row_spacing=KEYPAD_SPACING, column_spacing=KEYPAD_SPACING, halign=Gtk.Align.CENTER)
        keypad.set_margin_top(12)
        keypad.set_margin_bottom(12)
        keys = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "password", "0", "back"]
        self.keys = {}
        for i, key in enumerate(keys):
            if key == "back":
                button = Gtk.Button(icon_name="edit-clear-symbolic", **KEY_PROPS)
                button.update_property([Gtk.AccessibleProperty.LABEL], [_("Delete")])
                # As on the lock screen: a long press clears the PIN
                hold = Gtk.GestureLongPress()
                hold.connect("pressed", lambda *_a: self.on_key("clear"))
                button.add_controller(hold)
            elif key == "password":
                button = Gtk.Button(icon_name="input-keyboard-symbolic", **KEY_PROPS)
                button.update_property([Gtk.AccessibleProperty.LABEL], [_("Password")])
            else:
                button = Gtk.Button(label=key, **KEY_PROPS)
            button.connect("clicked", lambda _b, k=key: self.on_key(k))
            self.keys[key] = button
            cell = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
            cell.append(button)
            keypad.attach(cell, i % 3, i // 3, 1, 1)
        self.pin_box.append(keypad)
        self.pin_next = Gtk.Button(label=_("Continue"), css_classes=["pin-submit"], halign=Gtk.Align.CENTER,
                                   sensitive=False)
        self.pin_next.connect("clicked", lambda _b: self.on_key("next"))
        self.keys["next"] = self.pin_next
        self.pin_box.append(self.pin_next)
        box.append(self.pin_box)

        # The password: two fields and the on-screen keyboard instead of the keypad, as on the lock
        # screen; the keypad button goes back to the PIN
        self.password_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10, visible=False, width_request=300)
        self.password_box.set_margin_top(12)
        self.secret = Gtk.PasswordEntry(show_peek_icon=True, placeholder_text=_("Password"))
        self.again = Gtk.PasswordEntry(show_peek_icon=True, placeholder_text=_("Repeat password"))
        self.again.connect("activate", lambda _e: self.submit_password())
        self.secret.connect("activate", lambda _e: self.again.grab_focus())
        self.password_box.append(self.secret)
        self.password_box.append(self.again)
        row = Gtk.Box(spacing=16, halign=Gtk.Align.CENTER)
        row.set_margin_top(12)
        self.pin_mode = Gtk.Button(icon_name="input-dialpad-symbolic", css_classes=["pin-mode"], valign=Gtk.Align.CENTER)
        self.pin_mode.update_property([Gtk.AccessibleProperty.LABEL], [_("PIN")])
        self.pin_mode.connect("clicked", lambda _b: (feedback(), self.set_kind("pin")))
        row.append(self.pin_mode)
        self.password_next = Gtk.Button(label=_("Continue"), css_classes=["pin-submit"], valign=Gtk.Align.CENTER)
        self.password_next.connect("clicked", lambda _b: self.submit_password())
        row.append(self.password_next)
        self.password_box.append(row)
        box.append(self.password_box)
        self.update_first_prompt()

        # The PIN and the pages after it, one beside the other; back and on below the pages
        self.stack = Gtk.Stack(transition_type=Gtk.StackTransitionType.SLIDE_LEFT_RIGHT, transition_duration=250,
                               vhomogeneous=False, interpolate_size=True)
        self.stack.add_named(box, "pin")
        self.setup_pages = {}
        for step in STEPS[1:]:
            self.stack.add_named(self.make_setup_page(step), step)
        outer = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        outer.append(self.stack)
        nav = self.setup_nav = Gtk.Box(spacing=16, halign=Gtk.Align.CENTER, visible=False)
        nav.set_margin_top(8)
        back = Gtk.Button(icon_name="go-previous-symbolic", css_classes=["pin-mode"], valign=Gtk.Align.CENTER)
        back.connect("clicked", lambda _b: (feedback(), self.go_back()))
        self.setup_back = back
        nav.append(back)
        self.setup_next = Gtk.Button(css_classes=["pin-submit"], valign=Gtk.Align.CENTER)
        self.setup_next.connect("clicked", lambda _b: (feedback(), self.go_on()))
        nav.append(self.setup_next)
        outer.append(nav)
        return outer

    def make_setup_page(self, step):
        """A page after the PIN: a search (not for the few languages), the list as a card and, for the
        keyboard, a field to try it."""
        page = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12, width_request=360)
        widgets = {}
        if step != "language":
            search = Gtk.SearchEntry(css_classes=["setup-search"])
            search.connect("search-changed", lambda _e, st=step: self.fill_setup(st))
            self.keyboard_on_focus(search)
            page.append(search)
            widgets["search"] = search
        listbox = Gtk.ListBox(css_classes=["setup-list"], selection_mode=Gtk.SelectionMode.NONE,
                              valign=Gtk.Align.START)
        listbox.connect("row-activated", lambda _l, row, st=step: self.on_setup_row(st, row))
        scroller = Gtk.ScrolledWindow(hscrollbar_policy=Gtk.PolicyType.NEVER, propagate_natural_height=True,
                                      vexpand=True, child=listbox)
        page.append(scroller)
        widgets["list"] = listbox
        if step == "keyboard":
            attempt = Gtk.Entry(css_classes=["setup-try"])
            self.keyboard_on_focus(attempt)
            page.append(attempt)
            widgets["try"] = attempt
        self.setup_pages[step] = widgets
        return page

    def keyboard_on_focus(self, field):
        """Stevia in the chosen layout once the field has the focus: searching needs it too."""
        focus = Gtk.EventControllerFocus()
        focus.connect("enter", lambda _c: self.start_keyboard(self.choice["keyboard"]))
        field.add_controller(focus)

    # Rows of the lists: a title, a line below it, the time on the right (time zones), a check mark for
    # the chosen one

    def setup_row(self, value, title, subtitle="", time=""):
        row = Gtk.ListBoxRow()
        row.value = value
        box = Gtk.Box(spacing=12)
        texts = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2, hexpand=True, valign=Gtk.Align.CENTER)
        texts.append(Gtk.Label(label=title, xalign=0, css_classes=["setup-row-title"],
                               ellipsize=Pango.EllipsizeMode.END))
        if subtitle:
            texts.append(Gtk.Label(label=subtitle, xalign=0, css_classes=["setup-row-subtitle"],
                                   ellipsize=Pango.EllipsizeMode.END))
        box.append(texts)
        if time:
            box.append(Gtk.Label(label=time, css_classes=["setup-row-time"], valign=Gtk.Align.CENTER))
        check = Gtk.Image(icon_name="object-select-symbolic", css_classes=["setup-check"], pixel_size=20)
        box.append(check)
        row.check = check
        row.set_child(box)
        return row

    def section_row(self, text):
        row = Gtk.ListBoxRow(activatable=False, selectable=False)
        row.value = None
        row.set_child(Gtk.Label(label=text, xalign=0, css_classes=["setup-section"]))
        return row

    def fill_setup(self, step):
        widgets = self.setup_pages[step]
        listbox = widgets["list"]
        listbox.remove_all()
        query = widgets["search"].get_text().strip().casefold() if "search" in widgets else ""
        code = self.choice["language"]
        rows = []
        if step == "language":
            for entry in LANGUAGES:
                # The own name, below it the name in the language shown now if that differs
                other = _(LANGUAGE_NAMES[entry[0]])
                rows.append(self.setup_row(entry[0], entry[1], other if other != entry[1] else ""))
        elif step == "keyboard":
            if self.layouts is None:
                self.layouts = stevia_layouts_named()
            suggested, others = keyboard_choices(code, self.layouts, self.choice["keyboard"])
            if query:
                for item in suggested + others:
                    name = gettext.dgettext("xkeyboard-config", item[2])
                    if query in name.casefold() or query in item[0]:
                        rows.append(self.setup_row(item[0], name))
            else:
                for item in suggested:
                    rows.append(self.setup_row(item[0], gettext.dgettext("xkeyboard-config", item[2])))
        else:
            if self.countries is None:
                self.countries = read_countries()
            zones = [z for _c, z in self.zones]
            country = {z: c for c, z in self.zones}
            if query:
                found = []
                for zone in sorted(set(zones), key=city_of):
                    land = gettext.dgettext("iso_3166-1", self.countries.get(country.get(zone), ""))
                    if query in city_of(zone).casefold() or (land and query in land.casefold()):
                        found.append(zone)
                # Cities that begin with it first
                found.sort(key=lambda z: not city_of(z).casefold().startswith(query))
                chosen = found[:60]
            else:
                chosen = timezone_choices(code, self.zones, self.choice["timezone"])
            for zone in chosen:
                land = self.countries.get(country.get(zone), "")
                offset, now = zone_time(zone, self.time_format)
                subtitle = f"{gettext.dgettext('iso_3166-1', land)} · {offset}" if land else offset
                rows.append(self.setup_row(zone, city_of(zone), subtitle, now))
        for row in rows:
            listbox.append(row)
        if not rows:
            listbox.append(self.section_row(_("Nothing found")))
        widgets["rows"] = rows
        self.mark_chosen(step)

    def mark_chosen(self, step):
        for row in self.setup_pages[step]["rows"]:
            chosen = row.value == self.choice[step]
            row.check.set_opacity(1 if chosen else 0)
            if chosen:
                row.add_css_class("chosen")
            else:
                row.remove_css_class("chosen")

    def on_setup_row(self, step, row):
        if row.value is None:
            return
        feedback()
        self.choice[step] = row.value
        self.touched.add(step)
        if step == "language":
            set_ui_language(row.value)
            # The keyboard and time zone that go with it, unless chosen by hand on their pages already
            if "keyboard" not in self.touched:
                if self.layouts is None:
                    self.layouts = stevia_layouts_named()
                self.choice["keyboard"] = keyboard_choices(row.value, self.layouts, None)[0][0][0]
            if "timezone" not in self.touched:
                self.choice["timezone"] = (timezone_choices(row.value, self.zones, "UTC") or ["UTC"])[0]
            self.retranslate()
        elif step == "keyboard" and self.keyboard is not None:
            # The keyboard being tried shows the new layout
            self.stop_keyboard()
            self.start_keyboard(row.value)
        self.mark_chosen(step)

    def go_to(self, step, animate=True):
        """Shows the PIN (step "pin") or a page after it."""
        self.stop_keyboard()
        self.step = step
        setup = step != "pin"
        self.stack.set_transition_type(Gtk.StackTransitionType.SLIDE_LEFT_RIGHT if animate
                                       else Gtk.StackTransitionType.NONE)
        if setup:
            self.fill_setup(step)
        else:
            # PIN or password as chosen before, typed anew
            kind, self.kind = self.kind, None
            self.set_kind(kind)
        self.stack.set_visible_child_name(step)
        self.setup_nav.set_visible(setup)
        # The list takes the room the PIN page leaves around itself
        for spacer in self.spacers + [self.rows_scroller]:
            spacer.set_visible(not setup)
        self.first_box.set_vexpand(setup)
        self.column.set_margin_top(COLUMN_TOP_SETUP if setup else COLUMN_TOP_FIRST)
        self.status.set_opacity(0)
        self.mark_step()
        self.retranslate()

    def mark_step(self):
        index = STEPS.index(self.step)
        for i, dot in enumerate(self.dots_of_steps):
            for name, on in (("current", i == index), ("done", i < index)):
                if on:
                    dot.add_css_class(name)
                else:
                    dot.remove_css_class(name)

    def go_back(self):
        index = STEPS.index(self.step)
        if index > 0:
            self.go_to(STEPS[index - 1])

    def go_on(self):
        index = STEPS.index(self.step)
        if index + 1 < len(STEPS):
            self.go_to(STEPS[index + 1])
        else:
            self.stop_keyboard()
            self.submit(self.pending_secret)

    def retranslate(self):
        """The texts of the first start in the language chosen just now."""
        titles = {
            "pin": (_("Protect your phone"), _("Choose how to unlock it. Settings and every other question for the "
                                               "password ask for the same.")),
            "language": (_("Language"), _("The phone shows its texts in this language.")),
            "keyboard": (_("Keyboard"), _("The layout of the on-screen keyboard. More layouts can be added in "
                                          "Settings later.")),
            "timezone": (_("Time Zone"), _("The clock shows the time of this place.")),
        }
        if self.first:
            title, subtitle = titles[self.step]
            self.title.set_label(title)
            self.subtitle.set_label(subtitle)
        if self.step == "pin":
            self.update_first_prompt()
            return
        self.setup_next.set_label(_("Done") if self.step == STEPS[-1] else _("Continue"))
        self.setup_back.update_property([Gtk.AccessibleProperty.LABEL], [_("Back")])
        pages = self.setup_pages
        pages["keyboard"]["search"].set_placeholder_text(_("Search keyboards"))
        pages["keyboard"]["try"].set_placeholder_text(_("Type here to try it"))
        pages["timezone"]["search"].set_placeholder_text(_("Search for a city or country"))
        self.fill_setup(self.step)

    def fit_keypad(self, width, height):
        """Keypad buttons and digits as big as on Phosh's lock screen of this size."""
        if width <= 0 or height <= 0:
            return
        if self.keypad_css is None:
            self.keypad_css = Gtk.CssProvider()
            Gtk.StyleContext.add_provider_for_display(Gdk.Display.get_default(), self.keypad_css,
                                                      Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION + 1)
        self.keypad_css.load_from_string(keypad_css(keypad_button_size(width, height)))

    def set_kind(self, kind):
        if self.kind == kind:
            return
        self.kind, self.digits, self.first_pin = kind, "", None
        self.pin_box.set_visible(kind == "pin")
        self.password_box.set_visible(kind == "password")
        self.status.set_opacity(0)
        self.update_first_prompt()
        if kind == "password":
            self.start_keyboard(self.choice["keyboard"])
            self.secret.grab_focus()

    def update_first_prompt(self):
        if self.kind == "pin":
            self.first_prompt.set_label(_("Repeat the PIN.") if self.first_pin is not None
                                        else _("Choose a PIN of 4 to 12 digits."))
            self.dots.set_label("●" * len(self.digits))
            self.pin_next.set_sensitive(bool(self.digits))
        else:
            self.first_prompt.set_label(_("Choose a password of at least 6 characters."))

    def on_key(self, key):
        if self.password_timeout:
            return
        feedback()
        if key == "password":
            self.set_kind("password")
            return
        if key == "back":
            self.digits = self.digits[:-1]
        elif key == "clear":
            self.digits = ""
        elif key == "next":
            self.next_pin()
            return
        elif len(self.digits) < PIN_DIGITS[1]:
            self.digits += key
        self.update_first_prompt()

    def next_pin(self):
        if self.first_pin is None:
            problem = secret_problem("pin", self.digits, self.digits)
            if problem:
                self.show_status(problem, error=True)
                return
            self.first_pin, self.digits = self.digits, ""
            self.status.set_opacity(0)
            self.update_first_prompt()
            return
        problem = secret_problem("pin", self.first_pin, self.digits)
        if problem:
            self.first_pin, self.digits = None, ""
            self.update_first_prompt()
            self.show_status(problem, error=True)
            return
        self.pending_secret = self.first_pin
        self.go_to(STEPS[1])

    def submit_password(self):
        if self.password_timeout:
            return
        feedback()
        secret, again = self.secret.get_text(), self.again.get_text()
        problem = secret_problem("password", secret, again)
        if problem:
            self.show_status(problem, error=True)
            return
        self.pending_secret = secret
        self.go_to(STEPS[1])

    def start_keyboard(self, layout=None):
        """Stevia for the password and to try the keyboard: greetd's session has no Phosh to start it.
        GSettings of its own, with the keyboard turned on (the greeter's are in memory only), in the
        layout chosen on the keyboard page."""
        if self.keyboard is not None or TEST or not os.access(KEYBOARD, os.X_OK):
            return
        config = os.path.join(os.environ.get("XDG_RUNTIME_DIR") or "/tmp", "plinius-greeter-keyboard")
        try:
            os.makedirs(os.path.join(config, "glib-2.0/settings"), mode=0o700, exist_ok=True)
            with open(os.path.join(config, "glib-2.0/settings/keyfile"), "w", encoding="utf-8") as f:
                f.write("[org/gnome/desktop/a11y/applications]\nscreen-keyboard-enabled=true\n")
                if layout and re.fullmatch(r"[a-z]{2,8}(\+[A-Za-z0-9_-]+)?", layout):
                    f.write(f"\n[org/gnome/desktop/input-sources]\nsources=[('xkb', '{layout}')]\n")
            # XDG_SESSION_CLASS: Stevia offers no settings in a greeter (stevia-plinius 0014)
            env = dict(os.environ, GSETTINGS_BACKEND="keyfile", XDG_CONFIG_HOME=config,
                       XDG_SESSION_CLASS="greeter")
            self.keyboard = subprocess.Popen([KEYBOARD], env=env, stdin=subprocess.DEVNULL)
        except OSError as e:
            print(f"plinius-greeter: on-screen keyboard: {e}", file=sys.stderr)

    def stop_keyboard(self):
        if self.keyboard is None:
            return
        self.keyboard.terminate()
        try:
            self.keyboard.wait(timeout=2)
        except subprocess.TimeoutExpired:
            self.keyboard.kill()
        self.keyboard = None

    def result_stamp(self):
        try:
            st = os.stat(PASSWORD_RESULT)
            return st.st_mtime_ns, st.st_ino
        except OSError:
            return None

    def submit(self, secret):
        """Hands the PIN or password to root (plinius-greeter-config password) and waits for its answer."""
        self.result_before = self.result_stamp()
        try:
            if TEST:
                print(f"plinius-greeter: first {self.kind} for {self.first}, {self.choice}", flush=True)
            else:
                tmp = os.path.join(REQUEST_DIR, "password.tmp")
                fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
                with os.fdopen(fd, "w") as f:
                    json.dump({"user": self.first, "secret": secret, **self.choice}, f)
                os.replace(tmp, os.path.join(REQUEST_DIR, "password"))
        except OSError as e:
            print(f"plinius-greeter: cannot hand over the password: {e}", file=sys.stderr)
            self.password_failed(_("The password could not be set. Please try again."))
            return
        self.first_box.set_sensitive(False)
        self.show_status(_("Setting it up…"), busy=True)
        self.waited = 0
        self.password_timeout = GLib.timeout_add(500, self.check_result)

    def check_result(self):
        self.waited += 500
        stamp = self.result_stamp()
        if stamp is None or stamp == self.result_before:
            if self.waited >= PASSWORD_TIMEOUT_SECONDS * 1000:
                self.password_timeout = 0
                self.password_failed(_("The password could not be set. Please try again."))
                return GLib.SOURCE_REMOVE
            return GLib.SOURCE_CONTINUE
        self.password_timeout = 0
        try:
            with open(PASSWORD_RESULT, encoding="utf-8") as f:
                result = f.read(64).strip()
        except OSError:
            result = "failed"
        if result == "ok":
            # Root logs the account in now; as after a tap, try again should it not start
            self.choosing = Account(self.first)
            self.show_status(_("Starting…"), busy=True)
            self.start_timeout = GLib.timeout_add_seconds(START_TIMEOUT_SECONDS, self.fail)
        elif result == "same":
            self.password_failed(_("That is the password of the encryption. Choose another one: it is typed in "
                                   "view of others many times a day."))
        elif result == "invalid":
            self.password_failed(_("That cannot be used. A PIN has 4 to 12 digits, a password at least 6 characters."))
        else:
            self.password_failed(_("The password could not be set. Please try again."))
        return GLib.SOURCE_REMOVE

    def password_failed(self, text):
        self.first_box.set_sensitive(True)
        if self.step != "pin":
            # The PIN was refused at the end: choose it anew, the other pages keep what is chosen
            self.go_to("pin")
        self.digits, self.first_pin = "", None
        self.secret.set_text("")
        self.again.set_text("")
        self.update_first_prompt()
        self.show_status(text, error=True)

    # ----- logging in -----

    def choose(self, account):
        if self.choosing:
            return GLib.SOURCE_REMOVE
        self.choosing = account
        for name, tile in self.tiles.items():
            tile.set_can_target(False)
            tile.add_css_class("chosen" if name == account.name else "dimmed")
        self.show_status(_("Starting…"), busy=True)
        try:
            self.write_request(account.name)
        except OSError as e:
            print(f"plinius-greeter: cannot hand over {account.name}: {e}", file=sys.stderr)
            self.fail()
            return GLib.SOURCE_REMOVE
        # greetd ends this session once the account's session starts; if it does not, try again
        self.start_timeout = GLib.timeout_add_seconds(START_TIMEOUT_SECONDS, self.fail)
        return GLib.SOURCE_REMOVE

    def write_request(self, name):
        if TEST:
            print(f"plinius-greeter: request {name}", flush=True)
            return
        tmp = os.path.join(REQUEST_DIR, "request.tmp")
        fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
        with os.fdopen(fd, "w") as f:
            f.write(name + "\n")
        os.replace(tmp, os.path.join(REQUEST_DIR, "request"))

    def fail(self):
        self.start_timeout = 0
        self.choosing = None
        self.failed = True
        # The password is set by now (root removed first-start): the account is a tile from here on
        self.first = read_first_start()
        self.show_mode()
        self.first_box.set_sensitive(True)
        self.title.set_label(_("Who is using the phone?"))
        self.subtitle.set_label(_("Tap your account, then unlock it as usual."))
        self.fill()
        self.show_status(_("The phone could not start this account. Please try again."), error=True)
        # The idle timer may have run out while the account started (on_idle leaves the screen on
        # then): dark again after IDLE_SECONDS without a touch
        if not self.blanked:
            self.restart_idle()
        return GLib.SOURCE_REMOVE

    def show_status(self, text, busy=False, error=False):
        self.status_label.set_label(text)
        self.spinner.set_visible(busy)
        if error:
            self.status_label.add_css_class("error")
        else:
            self.status_label.remove_css_class("error")
        self.status.set_opacity(1)

    # ----- clock -----

    def update_clock(self):
        now = GLib.DateTime.new_now_local()
        self.clock.set_label(now.format(self.time_format).strip())
        # Translators: the date below the clock (GLib's strftime codes), e.g. "%A, %-d. %B" in German
        self.date.set_label(now.format(_("%A, %B %-d")))
        return GLib.SOURCE_CONTINUE

    # ----- power -----

    def make_power_menu(self):
        """Phosh's power menu without what only a session has (screenshot, restarting Phosh, lock,
        log out): a card over the darkened screen, the close button at its top right, Power Off and
        Restart one below the other."""
        backdrop = Gtk.Box(css_classes=["power-menu"], visible=False, can_target=True)
        # The close button's circle (40 px) sits on the card's corner, 3 px in from it
        holder = Gtk.Overlay(halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER, hexpand=True, vexpand=True)
        self.power_card = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=17, css_classes=["power-card"])
        for side in ("top", "bottom", "start", "end"):
            getattr(self.power_card, f"set_margin_{side}")(17)
        holder.set_child(self.power_card)
        close = Gtk.Button(child=Gtk.Image(icon_name="window-close-symbolic", pixel_size=20),
                           css_classes=["power-close"], halign=Gtk.Align.END, valign=Gtk.Align.START)
        close.update_property([Gtk.AccessibleProperty.LABEL], [_("_Cancel").replace("_", "")])
        close.connect("clicked", lambda _b: (feedback(), self.hide_power_menu()))
        holder.add_overlay(close)
        self.power_entries = {}
        for method, icon, label in (("PowerOff", "system-shutdown-symbolic", _("_Power Off")),
                                    ("Reboot", "system-reboot-symbolic", _("_Restart"))):
            row = Gtk.Box(spacing=12, halign=Gtk.Align.START, hexpand=True)
            row.set_margin_start(22)
            row.set_margin_end(22)
            row.append(Gtk.Image(icon_name=icon, pixel_size=24))
            row.append(Gtk.Label(label=label, use_underline=True))
            button = Gtk.Button(child=row, css_classes=["entry"])
            button.update_property([Gtk.AccessibleProperty.LABEL], [label.replace("_", "")])
            button.connect("clicked", lambda _b, m=method: self.power(m))
            self.power_entries[method] = button
            self.power_card.append(button)
        backdrop.append(holder)
        # A tap beside the card closes the menu
        tap = Gtk.GestureClick()
        tap.connect("released", lambda _g, _n, x, y: self.on_power_menu_tap(x, y))
        backdrop.add_controller(tap)
        return backdrop

    def show_power_menu(self):
        self.power_menu.set_visible(True)

    def hide_power_menu(self):
        self.power_menu.set_visible(False)

    def on_power_menu_tap(self, x, y):
        ok, bounds = self.power_card.compute_bounds(self.power_menu)
        if not ok or not bounds.contains_point(Graphene.Point().init(x, y)):
            self.hide_power_menu()

    def power(self, method):
        """Powers off or restarts at once, as asked in the menu (logind)."""
        feedback()
        self.hide_power_menu()
        if TEST:
            print(f"plinius-greeter: {method}", flush=True)
            return
        bus = Gio.bus_get_sync(Gio.BusType.SYSTEM)
        bus.call("org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager",
                 method, GLib.Variant("(b)", (False,)), None, Gio.DBusCallFlags.NONE, -1, None, None)

    # ----- dark screen -----

    def on_any_event(self, _controller, _event):
        if not self.blanked:
            self.restart_idle()
        return False

    def restart_idle(self):
        if self.idle_timeout:
            GLib.source_remove(self.idle_timeout)
        self.idle_timeout = GLib.timeout_add_seconds(IDLE_SECONDS, self.on_idle)

    def on_idle(self):
        self.idle_timeout = 0
        if not self.choosing:
            self.blank_screen()
        return GLib.SOURCE_REMOVE

    def blank_screen(self):
        if self.blanked:
            return
        self.blanked = True
        self.blank.set_visible(True)
        self.hide_power_menu()
        if self.dust is not None:
            self.dust.set_running(False)
        self.saved_brightness = set_backlight(0)

    def wake(self):
        if not self.blanked:
            return
        self.blanked = False
        self.blank.set_visible(False)
        if self.dust is not None:
            self.dust.set_running(bool(self.first))
        if self.saved_brightness is not None:
            set_backlight(self.saved_brightness)
            self.saved_brightness = None
        self.restart_idle()

    def on_key_pressed(self, _controller, keyval, _keycode, _state):
        if keyval == Gdk.KEY_Escape and self.power_menu.get_visible():
            self.hide_power_menu()
            return True
        if keyval != Gdk.KEY_PowerOff:
            return False
        if not self.power_key_timeout:
            self.power_key_long = False
            self.power_key_timeout = GLib.timeout_add(POWER_KEY_LONG_MS, self.on_power_key_long)
        return True

    def on_power_key_long(self):
        self.power_key_timeout = 0
        self.power_key_long = True
        self.wake()
        feedback()
        self.show_power_menu()
        return GLib.SOURCE_REMOVE

    def on_key_released(self, _controller, keyval, _keycode, _state):
        if keyval != Gdk.KEY_PowerOff:
            return
        if self.power_key_timeout:
            GLib.source_remove(self.power_key_timeout)
            self.power_key_timeout = 0
        if self.power_key_long:
            return
        # A short press turns the screen off and on, as on the lock screen
        if self.blanked:
            self.wake()
        else:
            self.blank_screen()


def backlight_device():
    """(subsystem, name) of the panel's light: the Plinius has an LED class device."""
    for subsystem in ("backlight", "leds"):
        base = f"/sys/class/{subsystem}"
        try:
            names = sorted(os.listdir(base))
        except OSError:
            continue
        if subsystem == "leds":
            names = [n for n in names if n == "lcd-backlight"]
        for name in names:
            if os.path.exists(os.path.join(base, name, "brightness")):
                return subsystem, name
    return None


def set_backlight(value):
    """Sets the panel's brightness through logind (allowed for the active session); returns the
    brightness before, None if there is no such device or logind refused."""
    if TEST:
        return None
    device = backlight_device()
    if device is None:
        return None
    subsystem, name = device
    try:
        with open(f"/sys/class/{subsystem}/{name}/brightness", encoding="ascii") as f:
            before = int(f.read().strip())
        bus = Gio.bus_get_sync(Gio.BusType.SYSTEM)
        bus.call_sync("org.freedesktop.login1", "/org/freedesktop/login1/session/auto",
                      "org.freedesktop.login1.Session", "SetBrightness",
                      GLib.Variant("(ssu)", (subsystem, name, value)), None, Gio.DBusCallFlags.NONE, 2000, None)
        return before
    except (OSError, ValueError, GLib.Error) as e:
        print(f"plinius-greeter: brightness: {e}", file=sys.stderr)
        return None


def main():
    setup_locale()
    setup_feedback()
    app = Adw.Application(application_id="org.plinius.Greeter", flags=Gio.ApplicationFlags.NON_UNIQUE)

    def activate(application):
        Adw.StyleManager.get_default().set_color_scheme(Adw.ColorScheme.FORCE_DARK)
        provider = Gtk.CssProvider()
        look = installation_look()
        provider.load_from_string(make_css(look))
        Gtk.StyleContext.add_provider_for_display(Gdk.Display.get_default(), provider,
                                                  Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
        window = Greeter(application, look)
        if not os.environ.get("PLINIUS_GREETER_WINDOWED"):
            window.fullscreen()
        window.present()

    app.connect("activate", activate)
    return app.run([sys.argv[0]])


if __name__ == "__main__":
    sys.exit(main())
