#!/usr/bin/env python3
"""
CODED7 - seal text, blogs, images or any file inside creepy glitch-art PNGs.

Security (format v2, shared with the CODED7 Android app)
  * Key:  Argon2id (128 MiB memory, 4 passes, 4 lanes, 32-byte random salt)
          over  built-in secret + SHA-512(password) + SHA-512(keyfile, optional)
  * Data: zlib -> padded to hide its size -> ChaCha20-Poly1305 -> AES-256-GCM
          (two independent 256-bit keys; both ciphers must break to read it)
  * Image: the ciphertext lives in the 2 lowest bits of every colour channel,
          scattered with a keyed Feistel permutation; every unused bit is random,
          so the whole picture is uniform noise underneath the art.

Usage
  coded7                                    open the window (needs PyQt6)
  coded7 encode -t "text" -o out.png        seal text      (asks for a password)
  coded7 encode -f photo.jpg -o out.png     seal any file  (txt, md, html, jpg, pdf...)
  coded7 decode out.png                     unseal
  -k KEYFILE on either command adds a keyfile (any file) as a second factor
  coded7 install                            add CODED7 to your app menu / dock
"""
import argparse
import getpass
import hashlib
import html
import time
import math
import os
import random
import secrets
import shutil
import struct
import subprocess
import sys
import zlib

import numpy as np
from PIL import Image, ImageDraw, ImageFont
from cryptography.exceptions import InvalidTag
from cryptography.hazmat.primitives.ciphers.aead import AESGCM, ChaCha20Poly1305
from cryptography.hazmat.primitives.kdf.argon2 import Argon2id
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt

# Shared by every copy of CODED7 (desktop + Android). Changing it breaks old images.
MASTER_SECRET = bytes.fromhex(
    "4cf458c3b4b8cbb2b75bce84a86befa213f53fd60f09f17ab2df2dcd57fcf8ad")

MAGIC2 = b"CD7\x02"
KIND_TEXT, KIND_FILE = 0, 1
SALT_LEN, NONCE_LEN, TAG_LEN = 32, 12, 16
HEADER_LEN = SALT_LEN + 4
ARGON_T, ARGON_M_KIB, ARGON_P = 4, 128 * 1024, 4
MIN_SIDE = 512
PW_ALPHABET = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789#%&*+=?@"

GLYPHS = (
    "!#$%&*+<=>?@^~|\\/{}[]()§¶†‡•◊"
    "ΑΒΓΔΘΛΞΠΣΦΨΩαβγδεζηθλμξπσφψω"
    "БГДЖЗИЛПФЦЧШЩЪЫЭЮЯбгджзилфцчшщъыэюя"
    "∀∂∃∅∇∈∉∋∏∑∓√∞∠∧∨∩∪∫∬∮≈≠≡≤≥⊂⊃⊕⊗⊥⋈⌘⌬⍟"
    "←↑→↓↔↕↯⇄⇌⇒⇔⇝⟁⟐⟡"
    "■□▲△▶▷▼▽◆◇○◎●◐◑◒◓◢◣◤◥★☆♠♣♥♦♮♯⚛⚡"
    "0123456789ABCDEF01010110"
    "░▒▓█▀▄▌▐┼╋╬╳"
    "אבגדהוזחטיכלמנסעפצקרשת"
    "ابتثجحخدذرزسشصضطظعغفقكلمنهوي"
    "ⴰⴱⴳⴷⴹⴻⴼⴽⵀⵃⵄⵅⵇⵉⵊⵍⵎⵏⵓⵔⵕⵖⵙⵚⵛⵜⵟⵡⵢⵣ"
)
WHISPERS = ["SIGNAL LOST", "NO CARRIER", "ERR0R", "NULL", "0xDEAD", "404", "ACCESS DENIED",
            "CORRUPTED", "SEGFAULT", "NaN", "UNDEFINED", "/dev/null", "CHECKSUM FAIL", "OVERFLOW",
            "DATA EXPUNGED", "STATIC", "NOTHING TO SEE HERE", "RETRY?"]

FONT_CANDIDATES = [
    "/usr/share/fonts/TTF/DejaVuSans.ttf",
    "/usr/share/fonts/TTF/DejaVuSans-Bold.ttf",
    "/usr/share/fonts/TTF/DejaVuSansMono-Bold.ttf",
    "/usr/share/fonts/noto/NotoSans-Regular.ttf",
    "/usr/share/fonts/noto/NotoSansSymbols-Bold.ttf",
    "/usr/share/fonts/noto/NotoSansSymbols2-Regular.ttf",
    "/usr/share/fonts/noto/NotoSansMath-Regular.ttf",
        "/usr/share/fonts/noto/NotoSansHebrew-Regular.ttf",
    "/usr/share/fonts/noto/NotoSansArabic-Regular.ttf",
    "/usr/share/fonts/noto/NotoSansTifinagh-Regular.ttf",
    "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
    "/usr/share/fonts/truetype/noto/NotoSans-Regular.ttf",
    "/usr/share/fonts/dejavu-sans-fonts/DejaVuSans.ttf",
]
BOLD_FONTS = ["/usr/share/fonts/TTF/DejaVuSans-Bold.ttf",
              "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
              "/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf"]


class Coded7Error(Exception):
    pass


# ================================================================ crypto ====

def _secret_material(password: str, keyfile: bytes | None) -> bytes:
    kf = hashlib.sha512(keyfile).digest() if keyfile else bytes(64)
    return MASTER_SECRET + hashlib.sha512(password.encode("utf-8")).digest() + kf


def _derive_keys(password: str, keyfile: bytes | None, salt: bytes):
    k = Argon2id(salt=salt, length=64, iterations=ARGON_T, lanes=ARGON_P,
                 memory_cost=ARGON_M_KIB).derive(_secret_material(password, keyfile))
    return k[:32], k[32:]


def _length_mask(salt: bytes) -> bytes:
    return hashlib.sha256(b"len" + MASTER_SECRET + salt).digest()[:4]


def _xor4(a: bytes, b: bytes) -> bytes:
    return bytes(x ^ y for x, y in zip(a, b))


def _padded_len(n: int) -> int:
    p2 = 1 << max(0, (n - 1).bit_length())
    q = max(4096, p2 // 8)
    return -(-n // q) * q


def _pack_inner(kind: int, name: str, data: bytes) -> bytes:
    name_b = name.encode("utf-8")[:65535]
    comp = zlib.compress(data, 9)
    core = MAGIC2 + struct.pack(">BH", kind, len(name_b)) + name_b + struct.pack(">I", len(comp)) + comp
    return core + os.urandom(_padded_len(len(core)) - len(core))


def _unpack_inner(inner: bytes):
    if inner[:4] != MAGIC2:
        raise Coded7Error("Unknown data format.")
    kind, nlen = struct.unpack(">BH", inner[4:7])
    name = inner[7:7 + nlen].decode("utf-8")
    (clen,) = struct.unpack(">I", inner[7 + nlen:11 + nlen])
    return kind, name, zlib.decompress(inner[11 + nlen:11 + nlen + clen])


def seal(kind: int, name: str, data: bytes, password: str, keyfile: bytes | None = None) -> bytes:
    salt = os.urandom(SALT_LEN)
    k_aes, k_cha = _derive_keys(password, keyfile, salt)
    aad = b"CD7v2" + salt
    n_aes, n_cha = os.urandom(NONCE_LEN), os.urandom(NONCE_LEN)
    inner_ct = ChaCha20Poly1305(k_cha).encrypt(n_cha, _pack_inner(kind, name, data), aad)
    body = n_aes + n_cha + AESGCM(k_aes).encrypt(n_aes, inner_ct, aad)
    return salt + _xor4(struct.pack(">I", len(body)), _length_mask(salt)) + body


def unseal(blob: bytes, password: str, keyfile: bytes | None = None):
    salt, body = blob[:SALT_LEN], blob[HEADER_LEN:]
    k_aes, k_cha = _derive_keys(password, keyfile, salt)
    aad = b"CD7v2" + salt
    n_aes, n_cha, ct = body[:NONCE_LEN], body[NONCE_LEN:2 * NONCE_LEN], body[2 * NONCE_LEN:]
    try:
        inner = ChaCha20Poly1305(k_cha).decrypt(n_cha, AESGCM(k_aes).decrypt(n_aes, ct, aad), aad)
    except InvalidTag:
        raise Coded7Error("bad key")
    return _unpack_inner(inner)


# ============================================== keyed pixel permutation ====
# Feistel network over [0, 2^(2h)) with cycle-walking down to [0, N).
# Identical to the Kotlin version in the Android app - do not change.

def _feistel_keys(w: int, h: int):
    return struct.unpack(">8I", hashlib.sha256(b"perm2" + MASTER_SECRET + struct.pack(">II", w, h)).digest())


def _round_f(r: np.ndarray, k: int) -> np.ndarray:
    m32 = np.uint64(0xFFFFFFFF)
    x = ((r ^ np.uint64(k)) * np.uint64(0x9E3779B1)) & m32
    x ^= x >> np.uint64(15)
    x = (x * np.uint64(0x85EBCA77)) & m32
    x ^= x >> np.uint64(13)
    return x


def _feistel(x: np.ndarray, hb: int, keys) -> np.ndarray:
    mask = np.uint64((1 << hb) - 1)
    left, right = x >> np.uint64(hb), x & mask
    for r in range(6):
        left, right = right, left ^ (_round_f(right, keys[r]) & mask)
    return (left << np.uint64(hb)) | right


def _slots(count: int, n: int, w: int, h: int) -> np.ndarray:
    """Slot index (0..n-1) for symbols 0..count-1."""
    keys = _feistel_keys(w, h)
    hb = 1
    while (1 << (2 * hb)) < n:
        hb += 1
    y = _feistel(np.arange(count, dtype=np.uint64), hb, keys)
    bad = y >= n
    while bad.any():
        y[bad] = _feistel(y[bad], hb, keys)
        bad = y >= n
    return y.astype(np.int64)


def _bytes_to_symbols(data: bytes) -> np.ndarray:
    bits = np.unpackbits(np.frombuffer(data, dtype=np.uint8))
    return (bits[0::2] << 1) | bits[1::2]


def _symbols_to_bytes(sym: np.ndarray) -> bytes:
    bits = np.empty(sym.size * 2, dtype=np.uint8)
    bits[0::2], bits[1::2] = (sym >> 1) & 1, sym & 1
    return np.packbits(bits).tobytes()


# ============================================================= the art =====

_GLYPH_TABLE = None


def _glyph_table():
    global _GLYPH_TABLE
    if _GLYPH_TABLE is None:
        _GLYPH_TABLE = {}
        for path in FONT_CANDIDATES:
            if not os.path.exists(path):
                continue
            try:
                f = ImageFont.truetype(path, 16)
            except OSError:
                continue
            tofu = {bytes(f.getmask(c)) for c in "\U0010fffd͸"}
            ok = [c for c in GLYPHS if bytes(f.getmask(c)) not in tofu]
            if ok:
                _GLYPH_TABLE[path] = ok
    return _GLYPH_TABLE


def _font(path, size, cache={}):
    key = (path, size)
    if key not in cache:
        try:
            cache[key] = ImageFont.truetype(path, size) if path else ImageFont.load_default(size)
        except OSError:
            cache[key] = ImageFont.load_default(size)
    return cache[key]


def _bold_font():
    return next((p for p in BOLD_FONTS if os.path.exists(p)), None)


def _zalgo(text, rnd, amount=3):
    out = []
    for ch in text:
        out.append(ch)
        for _ in range(rnd.randint(0, amount)):
            out.append(chr(rnd.choice(ZALGO_MARKS)))
    return "".join(out)


ZALGO_MARKS = [0x300, 0x301, 0x302, 0x303, 0x304, 0x306, 0x307, 0x308, 0x30A, 0x30B, 0x30C,
               0x323, 0x324, 0x325, 0x326, 0x327, 0x328, 0x330, 0x331, 0x332, 0x334, 0x335, 0x336, 0x337, 0x338]
BLOOD = [(150, 0, 20), (110, 0, 12), (200, 10, 40), (90, 0, 30)]
SICK = [(120, 255, 90), (180, 255, 60), (60, 200, 120)]
BONE = [(220, 210, 190), (200, 190, 170), (235, 228, 210)]


def _draw_eye(img, cx, cy, r, rnd):
    w, h = int(r * 2.2), int(r * rnd.uniform(1.0, 1.5))
    layer = Image.new("RGBA", (w, h), (0, 0, 0, 0))
    d = ImageDraw.Draw(layer)
    sclera = rnd.choice(BONE + [(190, 170, 140)])
    d.ellipse([0, 0, w - 1, h - 1], fill=sclera + (255,))
    for _ in range(rnd.randint(4, 12)):                      # veins
        a = rnd.uniform(0, 2 * math.pi)
        x, y = w / 2 + math.cos(a) * w / 2, h / 2 + math.sin(a) * h / 2
        pts = [(x, y)]
        for _ in range(rnd.randint(3, 7)):
            x += (w / 2 - x) * 0.25 + rnd.uniform(-6, 6)
            y += (h / 2 - y) * 0.25 + rnd.uniform(-6, 6)
            pts.append((x, y))
        d.line(pts, fill=rnd.choice(BLOOD) + (200,), width=rnd.randint(1, 2))
    ir = h * rnd.uniform(0.32, 0.45)
    ix, iy = w / 2 + rnd.uniform(-w * 0.18, w * 0.18), h / 2 + rnd.uniform(-h * 0.08, h * 0.08)
    iris = rnd.choice([(170, 0, 25), (120, 230, 50), (230, 190, 0), (25, 25, 25), (210, 215, 230), (90, 0, 140)])
    d.ellipse([ix - ir, iy - ir, ix + ir, iy + ir], fill=iris + (255,), outline=(20, 0, 0, 255), width=max(1, int(ir / 6)))
    for _ in range(14):                                       # iris fibres
        a = rnd.uniform(0, 2 * math.pi)
        d.line([ix + math.cos(a) * ir * 0.3, iy + math.sin(a) * ir * 0.3,
                ix + math.cos(a) * ir * 0.95, iy + math.sin(a) * ir * 0.95],
               fill=tuple(max(0, c - 60) for c in iris) + (180,), width=1)
    if rnd.random() < 0.5:                                    # slit pupil
        d.ellipse([ix - ir * 0.15, iy - ir * 0.85, ix + ir * 0.15, iy + ir * 0.85], fill=(0, 0, 0, 255))
    else:
        pr = ir * rnd.uniform(0.3, 0.6)
        d.ellipse([ix - pr, iy - pr, ix + pr, iy + pr], fill=(0, 0, 0, 255))
    d.ellipse([ix - ir * 0.55, iy - ir * 0.6, ix - ir * 0.25, iy - ir * 0.3], fill=(255, 255, 255, 220))
    mask = Image.new("L", (w, h), 0)
    ImageDraw.Draw(mask).ellipse([0, 0, w - 1, h - 1], fill=255)
    layer.putalpha(Image.eval(mask, lambda v: v * rnd.randint(180, 255) // 255))
    ImageDraw.Draw(layer).ellipse([0, 0, w - 1, h - 1], outline=(10, 0, 0, 255), width=max(2, int(r / 10)))
    if rnd.random() < 0.35:                                   # rotated eye
        layer = layer.rotate(rnd.choice([90, -90, rnd.uniform(-40, 40)]), expand=True)
    img.alpha_composite(layer, (int(cx - layer.width / 2), int(cy - layer.height / 2)))


def _draw_rings(d, cx, cy, R, rnd, table=None):
    """Radar / target rings with tick marks - techy, not spooky."""
    col = rnd.choice(BLOOD + SICK[:1]) + (rnd.randint(90, 180),)
    lw = max(1, int(R / 45))
    for f in (1.0, 0.82, 0.5):
        d.ellipse([cx - R * f, cy - R * f, cx + R * f, cy + R * f], outline=col, width=lw)
    for i in range(72):
        a = 2 * math.pi * i / 72
        l = 0.9 if i % 6 else 0.84
        d.line([cx + math.cos(a) * R * l, cy + math.sin(a) * R * l, cx + math.cos(a) * R, cy + math.sin(a) * R], fill=col, width=lw)
    d.line([cx - R, cy, cx + R, cy], fill=col, width=lw)
    d.line([cx, cy - R, cx, cy + R], fill=col, width=lw)
    start = rnd.uniform(0, 360)
    d.arc([cx - R * 0.66, cy - R * 0.66, cx + R * 0.66, cy + R * 0.66], start, start + rnd.uniform(40, 160), fill=col, width=lw * 3)
    d.ellipse([cx - R * 0.05, cy - R * 0.05, cx + R * 0.05, cy + R * 0.05], fill=col)


def _draw_crack(d, x, y, length, angle, width, rnd, depth=0):
    for _ in range(int(length)):
        nx, ny = x + math.cos(angle) * 6, y + math.sin(angle) * 6
        d.line([x, y, nx, ny], fill=(rnd.randint(0, 25), 0, 0, 230), width=max(1, int(width)))
        x, y = nx, ny
        angle += rnd.uniform(-0.5, 0.5)
        width *= 0.985
        if depth < 3 and rnd.random() < 0.06:
            _draw_crack(d, x, y, length * 0.5, angle + rnd.uniform(-1.2, 1.2), width * 0.7, rnd, depth + 1)


def _post_fx(arr: np.ndarray, rnd) -> np.ndarray:
    h, w, _ = arr.shape
    a = arr.astype(np.int16)
    for _ in range(rnd.randint(6, 6 + h // 40)):              # glitch slices
        y0 = rnd.randint(0, h - 1)
        y1 = min(h, y0 + rnd.randint(1, max(2, h // 25)))
        a[y0:y1] = np.roll(a[y0:y1], rnd.randint(-w // 6, w // 6), axis=1)
        if rnd.random() < 0.3:
            a[y0:y1, :, rnd.randint(0, 2)] += rnd.randint(40, 120)
    sh = max(1, w // 300)                                    # chromatic aberration
    a[:, :, 0] = np.roll(a[:, :, 0], sh, axis=1)
    a[:, :, 2] = np.roll(a[:, :, 2], -sh, axis=1)
    a[::3] = a[::3] * 3 // 5                                 # scanlines
    yy, xx = np.mgrid[0:h, 0:w]                              # vignette
    r2 = ((xx - w / 2) / (w / 2)) ** 2 + ((yy - h / 2) / (h / 2)) ** 2
    vig = np.clip(1.15 - 0.55 * r2, 0.25, 1.0)
    a = (a * vig[:, :, None]).astype(np.int16)
    a += np.frombuffer(os.urandom(h * w * 3), dtype=np.uint8).reshape(h, w, 3).astype(np.int16) // 8 - 16
    return np.clip(a, 0, 255).astype(np.uint8)


def draw_art(w: int, h: int) -> Image.Image:
    rnd = random.SystemRandom()
    noise = np.frombuffer(os.urandom(w * h * 3), dtype=np.uint8).reshape(h, w, 3)
    tint = np.array(rnd.choice([(60, 0, 8), (10, 30, 12), (35, 0, 45), (20, 20, 28)]), dtype=np.uint16)
    base = (noise.astype(np.uint16) * 45 // 255 + tint).astype(np.uint8)
    img = Image.fromarray(base, "RGB").convert("RGBA")
    d = ImageDraw.Draw(img, "RGBA")
    table = _glyph_table()
    paths = list(table)
    area, short = w * h, min(w, h)

    for _ in range(max(2, area // 400_000)):                  # big faint target rings
        _draw_rings(d, rnd.randint(0, w), rnd.randint(0, h), rnd.randint(short // 6, short // 2), rnd, table)

    for _ in range(area // 9000):                             # shards
        x, y, s = rnd.randint(-40, w), rnd.randint(-40, h), rnd.randint(8, max(12, short // 8))
        col = rnd.choice(BLOOD + SICK + [(30, 30, 40)]) + (rnd.randint(25, 120),)
        if rnd.random() < 0.6:
            d.polygon([(x + rnd.randint(-s, s), y + rnd.randint(-s, s)) for _ in range(3)], fill=col)
        else:
            d.rectangle([x, y, x + s * 3, y + rnd.randint(1, 5)], fill=col)

    rain_font = 14
    for _ in range(max(6, w // 30)):                          # glyph rain
        if not paths:
            break
        path = rnd.choice(paths)
        f = _font(path, rain_font)
        x, y = rnd.randint(0, w), rnd.randint(-h // 2, h)
        col = rnd.choice(SICK + BLOOD)
        n = rnd.randint(5, 40)
        for i in range(n):
            alpha = int(255 * (1 - i / n))
            d.text((x, y - i * (rain_font + 2)), rnd.choice(table[path]), font=f, fill=col + (alpha,))

    for _ in range(area // 1800):                             # scattered symbols
        size = rnd.choice([10, 12, 14, 18, 24, 32, 48, 64])
        if paths:
            path = rnd.choice(paths)
            f, chars = _font(path, size), table[path]
        else:
            f, chars = _font(None, size), "!#$%&*+<=>?@^~|/{}[]()"
        text = "".join(rnd.choice(chars) for _ in range(rnd.choice([1, 1, 2, 3])))
        d.text((rnd.randint(-10, w), rnd.randint(-10, h)), text, font=f,
               fill=rnd.choice(BLOOD + SICK + BONE) + (rnd.randint(70, 230),))

    for _ in range(max(1, area // 350_000)):                  # cracks
        _draw_crack(d, rnd.randint(0, w), rnd.randint(0, h), rnd.randint(30, 120),
                    rnd.uniform(0, 2 * math.pi), rnd.uniform(2, 5), rnd)

    for _ in range(max(2, area // 120_000)):                  # eyes
        _draw_eye(img, rnd.randint(0, w), rnd.randint(0, h), rnd.randint(max(14, short // 30), max(20, short // 7)), rnd)

    bold = _bold_font()
    for _ in range(max(2, area // 200_000)):                  # whispers
        size = rnd.randint(max(14, short // 40), max(20, short // 12))
        text = rnd.choice(WHISPERS)
        if rnd.random() < 0.6:
            text = _zalgo(text, rnd)
        d.text((rnd.randint(0, max(1, w - size * 5)), rnd.randint(0, h)), text, font=_font(bold, size),
               fill=rnd.choice(BLOOD + BONE) + (rnd.randint(60, 200),))

    return Image.fromarray(_post_fx(np.array(img.convert("RGB")), rnd), "RGB")


def draw_noise(w: int, h: int) -> Image.Image:
    """Plain colour static - looks like a dead TV channel."""
    rnd = random.SystemRandom()
    noise = np.frombuffer(os.urandom(w * h * 3), dtype=np.uint8).reshape(h, w, 3).astype(np.uint16)
    tint = np.array([rnd.randint(0, 80) for _ in range(3)], dtype=np.uint16)
    return Image.fromarray(((noise * 3 + tint * 4) // 4).clip(0, 255).astype(np.uint8), "RGB")


def draw_mosaic(w: int, h: int) -> Image.Image:
    """Random pixel blocks in a harmonious palette."""
    import colorsys
    rnd = random.SystemRandom()
    hue = rnd.random()
    palette = []
    for i in range(6):
        hh = (hue + rnd.uniform(-0.08, 0.08) + (0.5 if i == 5 else 0)) % 1.0
        r, g, b = colorsys.hls_to_rgb(hh, rnd.uniform(0.15, 0.65), rnd.uniform(0.35, 0.85))
        palette.append((int(r * 255), int(g * 255), int(b * 255)))
    pal = np.array(palette, dtype=np.uint8)
    block = rnd.choice([6, 8, 10, 12, 16])
    gh, gw = -(-h // block), -(-w // block)
    idx = np.frombuffer(os.urandom(gh * gw), dtype=np.uint8).reshape(gh, gw) % len(palette)
    grid = pal[idx]
    big = np.repeat(np.repeat(grid, block, axis=0), block, axis=1)[:h, :w].astype(np.int16)
    big += np.frombuffer(os.urandom(w * h * 3), dtype=np.uint8).reshape(h, w, 3).astype(np.int16) // 16 - 8
    return Image.fromarray(big.clip(0, 255).astype(np.uint8), "RGB")


ART_STYLES = {
    "glitch": ("Glitch art", draw_art),
    "mosaic": ("Pixel mosaic", draw_mosaic),
    "noise": ("Static noise", draw_noise),
}


def make_icon(size: int = 256) -> Image.Image:
    """Padlock over a blue pixel mosaic."""
    s = size
    rng = random.Random(7)
    pal = [(22, 40, 96), (32, 64, 150), (58, 110, 230), (79, 140, 255), (24, 120, 150), (16, 28, 64)]
    bg = Image.new("RGB", (s, s))
    d = ImageDraw.Draw(bg)
    n = 8
    cell = s / n
    for i in range(n):
        for j in range(n):
            d.rectangle([i * cell, j * cell, (i + 1) * cell, (j + 1) * cell], fill=rng.choice(pal))
    mask = Image.new("L", (s, s), 0)
    ImageDraw.Draw(mask).rounded_rectangle([0, 0, s - 1, s - 1], radius=s // 5, fill=255)
    img = Image.new("RGBA", (s, s), (0, 0, 0, 0))
    img.paste(bg, (0, 0), mask)
    shade = Image.new("RGBA", (s, s), (8, 12, 24, 90))
    img.paste(shade, (0, 0), Image.eval(mask, lambda v: v * 90 // 255))
    d = ImageDraw.Draw(img)
    white = (245, 248, 255, 255)
    lw = int(s * 0.075)
    d.arc([s * 0.33, s * 0.2, s * 0.67, s * 0.58], 180, 360, fill=white, width=lw)
    d.rectangle([s * 0.33, s * 0.39, s * 0.33 + lw, s * 0.5], fill=white)
    d.rectangle([s * 0.67 - lw, s * 0.39, s * 0.67, s * 0.5], fill=white)
    d.rounded_rectangle([s * 0.26, s * 0.46, s * 0.74, s * 0.8], radius=int(s * 0.06), fill=white)
    d.ellipse([s * 0.455, s * 0.55, s * 0.545, s * 0.64], fill=(22, 40, 96, 255))
    d.rectangle([s * 0.48, s * 0.6, s * 0.52, s * 0.71], fill=(22, 40, 96, 255))
    return img


# ===================================================== image <-> bytes =====

def _embed(blob: bytes, style: str = "glitch") -> Image.Image:
    need_slots = len(blob) * 4
    side = max(MIN_SIDE, math.ceil(math.sqrt(need_slots / 3 * 1.02)) + 1)
    w, h = side + random.SystemRandom().randint(0, side // 4), side
    painter = ART_STYLES.get(style, ART_STYLES["glitch"])[1]
    arr = np.array(painter(w, h), dtype=np.uint8)
    flat = arr.reshape(-1)
    flat[:] = (flat & 0xFC) | (np.frombuffer(os.urandom(flat.size), dtype=np.uint8) & 3)
    idx = _slots(need_slots, flat.size, w, h)
    flat[idx] = (flat[idx] & 0xFC) | _bytes_to_symbols(blob)
    return Image.fromarray(arr, "RGB")


def _extract_v2(flat: np.ndarray, w: int, h: int) -> bytes:
    n = flat.size
    head = _symbols_to_bytes(flat[_slots(HEADER_LEN * 4, n, w, h)] & 3)
    salt = head[:SALT_LEN]
    (body_len,) = struct.unpack(">I", _xor4(head[SALT_LEN:HEADER_LEN], _length_mask(salt)))
    total = HEADER_LEN + body_len
    if body_len < 2 * NONCE_LEN + 2 * TAG_LEN + 11 or total * 4 > n:
        raise Coded7Error("no v2 data")
    return _symbols_to_bytes(flat[_slots(total * 4, n, w, h)] & 3)


def _decode_v1(flat: np.ndarray, w: int, h: int, password: str):
    """Images made by the first CODED7 version (scrypt + AES-GCM)."""
    seed = hashlib.sha256(b"perm" + MASTER_SECRET + struct.pack(">II", w, h)).digest()
    perm = np.random.default_rng(int.from_bytes(seed, "big")).permutation(flat.size)
    head = _symbols_to_bytes(flat[perm[:80]] & 3)
    salt = head[:16]
    mask = hashlib.sha256(b"len" + MASTER_SECRET + salt).digest()[:4]
    (body_len,) = struct.unpack(">I", _xor4(head[16:20], mask))
    if body_len < 28 or (20 + body_len) * 4 > flat.size:
        raise Coded7Error("no v1 data")
    blob = _symbols_to_bytes(flat[perm[:(20 + body_len) * 4]] & 3)
    key = Scrypt(salt=salt, length=32, n=2**15, r=8, p=1).derive(MASTER_SECRET + password.encode())
    try:
        plain = AESGCM(key).decrypt(blob[20:32], blob[32:], salt)
    except InvalidTag:
        raise Coded7Error("bad key")
    if plain[:4] != b"CD7\x01":
        raise Coded7Error("bad data")
    kind, nlen = struct.unpack(">BH", plain[4:7])
    return kind, plain[7:7 + nlen].decode("utf-8"), zlib.decompress(plain[7 + nlen:])


# ============================================================ public API ====

def check_password(password: str):
    """Passwords are optional. Without one, any copy of CODED7 can open the image."""
    if not isinstance(password, str):
        raise Coded7Error("Invalid password.")


def encode(kind: int, name: str, data: bytes, password: str, keyfile: bytes | None = None,
           style: str = "glitch") -> Image.Image:
    check_password(password)
    return _embed(seal(kind, name, data, password, keyfile), style)


def decode(img: Image.Image, password: str, keyfile: bytes | None = None):
    img = img.convert("RGB")
    w, h = img.size
    flat = np.array(img, dtype=np.uint8).reshape(-1)
    try:
        return unseal(_extract_v2(flat, w, h), password, keyfile)
    except Coded7Error:
        pass
    if not keyfile:
        try:
            return _decode_v1(flat, w, h, password)
        except Coded7Error:
            pass
    raise Coded7Error("Could not decrypt: wrong password or keyfile, or the image was modified (resized or recompressed).")


def generate_password() -> str:
    raw = "".join(secrets.choice(PW_ALPHABET) for _ in range(24))
    return "-".join(raw[i:i + 6] for i in range(0, 24, 6))


def password_bits(pw: str) -> float:
    pools = 0
    if any(c.islower() for c in pw): pools += 26
    if any(c.isupper() for c in pw): pools += 26
    if any(c.isdigit() for c in pw): pools += 10
    if any(not c.isalnum() and ord(c) < 128 for c in pw): pools += 33
    if any(ord(c) >= 128 for c in pw): pools += 100
    if not pw:
        return 0.0
    unique = len(set(pw)) / len(pw)
    return len(pw) * math.log2(max(pools, 2)) * (0.5 + 0.5 * unique)


def _safe_name(name: str) -> str:
    name = os.path.basename(name.replace("\\", "/")).strip()
    return name if name and name not in (".", "..") else "decoded.bin"


def _unique_path(path: str) -> str:
    base, ext = os.path.splitext(path)
    i = 1
    while os.path.exists(path):
        path = f"{base}_{i}{ext}"
        i += 1
    return path


# =============================================================== install ====

def install():
    here = os.path.realpath(__file__)
    bindir = os.path.expanduser("~/.local/bin")
    icondir = os.path.expanduser("~/.local/share/icons/hicolor/256x256/apps")
    appdir = os.path.expanduser("~/.local/share/applications")
    for p in (bindir, icondir, appdir):
        os.makedirs(p, exist_ok=True)
    target = os.path.join(bindir, "coded7")
    if os.path.realpath(target) != here:
        shutil.copy2(here, target)
        os.chmod(target, 0o755)
    icon = os.path.join(icondir, "coded7.png")
    make_icon(256).save(icon)
    with open(os.path.join(appdir, "coded7.desktop"), "w") as f:
        f.write("[Desktop Entry]\nType=Application\nName=CODED7\n"
                "GenericName=Image Encryption\n"
                "Comment=Encrypt text and files into images\n"
                f"Exec={target} gui\nIcon={icon}\nTerminal=false\n"
                "Categories=Utility;Security;\nStartupWMClass=CODED7\n")
    for cmd in (["update-desktop-database", appdir], ["kbuildsycoca6"], ["kbuildsycoca5"]):
        if shutil.which(cmd[0]):
            subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    print(f"Installed. Program: {target}\nCODED7 is now in your app menu - right-click it -> 'Pin to Task Manager' for the dock.")
    return 0


# =================================================================== CLI ====

def _read_keyfile(path):
    if not path:
        return None
    with open(path, "rb") as f:
        data = f.read()
    if not data:
        raise Coded7Error("Keyfile is empty.")
    return data


def cli(argv=None):
    ap = argparse.ArgumentParser(prog="coded7", description="Seal text or files inside glitch-art noise images.")
    sub = ap.add_subparsers(dest="cmd")
    e = sub.add_parser("encode", help="text/file -> image")
    src = e.add_mutually_exclusive_group()
    src.add_argument("-t", "--text", help="text to hide")
    src.add_argument("-f", "--file", help="any file to hide (txt, md, html, png, jpg, pdf...)")
    e.add_argument("-o", "--output", default="coded7.png", help="output PNG (default coded7.png)")
    e.add_argument("-k", "--keyfile", help="use any file as an extra key")
    e.add_argument("-s", "--style", choices=list(ART_STYLES), default="glitch", help="look of the image")
    d = sub.add_parser("decode", help="image -> text/file")
    d.add_argument("image")
    d.add_argument("-o", "--output", help="where to save the result")
    d.add_argument("-k", "--keyfile", help="keyfile used when sealing")
    sub.add_parser("gui", help="open the window")
    sub.add_parser("install", help="add CODED7 to the app menu / dock")
    sub.add_parser("genpass", help="print a strong random password")
    a = ap.parse_args(argv)

    if a.cmd in (None, "gui"):
        return gui()
    if a.cmd == "install":
        return install()
    if a.cmd == "genpass":
        print(generate_password())
        return 0
    try:
        kf = _read_keyfile(a.keyfile)
        if a.cmd == "encode":
            if a.file:
                with open(a.file, "rb") as fh:
                    kind, name, data = KIND_FILE, os.path.basename(a.file), fh.read()
            elif a.text is not None:
                kind, name, data = KIND_TEXT, "", a.text.encode("utf-8")
            else:
                if sys.stdin.isatty():
                    print("Type/paste your text, then press Ctrl+D:", file=sys.stderr)
                kind, name, data = KIND_TEXT, "", sys.stdin.buffer.read()
            pw = getpass.getpass("Password (Enter for none): ")
            if pw and pw != getpass.getpass("Repeat password: "):
                raise Coded7Error("Passwords do not match.")
            if not pw:
                print("No password set. Anyone with CODED7 can open this image.", file=sys.stderr)
            out = a.output if a.output.lower().endswith(".png") else a.output + ".png"
            img = encode(kind, name, data, pw, kf, a.style)
            img.save(out, "PNG")
            print(f"Sealed into {out}  ({img.size[0]}x{img.size[1]})")
        else:
            pw = getpass.getpass("Password (Enter if none): ")
            kind, name, data = decode(Image.open(a.image), pw, kf)
            if kind == KIND_TEXT and not a.output:
                sys.stdout.write(data.decode("utf-8", errors="replace"))
                if not data.endswith(b"\n"):
                    sys.stdout.write("\n")
            else:
                out = a.output or _unique_path(_safe_name(name or "decoded.txt"))
                with open(out, "wb") as fh:
                    fh.write(data)
                print(f"Unsealed -> {out}  ({len(data)} bytes)")
    except (Coded7Error, OSError, ValueError) as ex:
        print(f"Error: {ex}", file=sys.stderr)
        return 1
    return 0


# =================================================================== GUI ====

APP_VERSION = "2.1"


def _fmt_size(n: int) -> str:
    for unit in ("B", "KB", "MB", "GB"):
        if n < 1024 or unit == "GB":
            return f"{n:.0f} {unit}" if unit == "B" else f"{n:.1f} {unit}"
        n /= 1024


def gui():
    try:
        from PyQt6.QtCore import Qt, QThread, QTimer, QUrl, pyqtSignal
        from PyQt6.QtGui import QDesktopServices, QGuiApplication, QIcon, QKeySequence, QPixmap, QShortcut
        from PyQt6.QtWidgets import (
            QApplication, QButtonGroup, QCheckBox, QComboBox, QFileDialog, QFrame, QGridLayout,
            QHBoxLayout, QLabel, QLineEdit, QMainWindow, QMessageBox, QPlainTextEdit, QProgressBar,
            QPushButton, QSizePolicy, QStackedWidget, QVBoxLayout, QWidget)
    except ImportError:
        print("The window needs PyQt6:  sudo pacman -S python-pyqt6   (or: pip install PyQt6)", file=sys.stderr)
        return 1
    import io

    ACCENT = "#4f8cff"
    QSS = f"""
    QMainWindow, #Page {{ background: #0f1115; }}
    QWidget {{ color: #e6e9ef; font-size: 10.5pt; }}
    QToolTip {{ background: #1c222c; color: #e6e9ef; border: 1px solid #2a313d; }}
    #Sidebar {{ background: #0b0d10; border-right: 1px solid #1f242c; }}
    #Brand {{ font-size: 15pt; font-weight: 700; letter-spacing: 1px; }}
    #BrandSub, #Muted {{ color: #8b93a1; }}
    #Small {{ color: #8b93a1; font-size: 9pt; }}
    #H1 {{ font-size: 19pt; font-weight: 700; }}
    #Section {{ color: #8b93a1; font-size: 8.5pt; font-weight: 700; letter-spacing: 1px; }}
    #Error {{ color: #ff6b6b; }}
    #Ok {{ color: #4ade80; }}
    #Card {{ background: #151920; border: 1px solid #232934; border-radius: 12px; }}
    #Card QLabel {{ background: transparent; }}
    QLineEdit, QPlainTextEdit, QComboBox {{
        background: #0f1217; border: 1px solid #2a313d; border-radius: 8px; padding: 7px 10px;
        selection-background-color: {ACCENT}; }}
    QLineEdit:focus, QPlainTextEdit:focus, QComboBox:focus {{ border-color: {ACCENT}; }}
    QComboBox::drop-down {{ border: none; width: 22px; }}
    QComboBox QAbstractItemView {{ background: #151920; border: 1px solid #2a313d; selection-background-color: #1a2233; }}
    QPushButton {{ background: #1c222c; border: 1px solid #2a313d; border-radius: 8px; padding: 7px 14px; font-weight: 600; }}
    QPushButton:hover {{ background: #232a36; }}
    QPushButton:disabled {{ color: #59616d; background: #161a21; }}
    QPushButton#Primary {{ background: {ACCENT}; border: none; color: white; padding: 10px 22px; }}
    QPushButton#Primary:hover {{ background: #6a9dff; }}
    QPushButton#Primary:disabled {{ background: #26314a; color: #7f8db0; }}
    QPushButton#Nav {{ text-align: left; padding: 10px 14px; border: none; border-radius: 8px;
        background: transparent; color: #aab2bf; font-weight: 600; }}
    QPushButton#Nav:hover {{ background: #161a21; color: #e6e9ef; }}
    QPushButton#Nav:checked {{ background: #1a2233; color: {ACCENT}; }}
    QPushButton#Seg {{ padding: 6px 18px; }}
    QPushButton#Seg:checked {{ background: #1a2233; color: {ACCENT}; border-color: {ACCENT}; }}
    QPushButton#Link {{ background: transparent; border: none; color: {ACCENT}; padding: 2px 4px; }}
    QPushButton#Link:hover {{ text-decoration: underline; }}
    QProgressBar {{ background: #1c222c; border: none; border-radius: 3px; max-height: 6px; min-height: 6px; }}
    QProgressBar::chunk {{ border-radius: 3px; background: {ACCENT}; }}
    #Drop {{ border: 2px dashed #2f3745; border-radius: 12px; background: #11151b; }}
    #Drop[hover="true"] {{ border-color: {ACCENT}; background: #141b27; }}
    #Preview {{ background: #0f1217; border: 1px solid #232934; border-radius: 10px; }}
    #Console {{ background: #05070a; color: #3ddc84; border: 1px solid #1d2a22; border-radius: 10px;
        font-family: "JetBrains Mono", "DejaVu Sans Mono", monospace; font-size: 9.5pt; padding: 6px; }}
    QStatusBar {{ background: #0b0d10; color: #8b93a1; border-top: 1px solid #1f242c; }}
    QStatusBar QLabel {{ color: #8b93a1; }}
    QCheckBox {{ color: #aab2bf; spacing: 6px; }}
    QMessageBox {{ background: #151920; }}
    """

    def pil_to_pixmap(img, max_side):
        im = img.copy()
        im.thumbnail((max_side, max_side))
        buf = io.BytesIO()
        im.save(buf, "PNG")
        pm = QPixmap()
        pm.loadFromData(buf.getvalue())
        return pm

    def label(text="", name=None, wrap=False):
        lb = QLabel(text)
        if name:
            lb.setObjectName(name)
        lb.setWordWrap(wrap)
        return lb

    def button(text, name=None, slot=None, tip=None):
        b = QPushButton(text)
        if name:
            b.setObjectName(name)
        if slot:
            b.clicked.connect(slot)
        if tip:
            b.setToolTip(tip)
        b.setCursor(Qt.CursorShape.PointingHandCursor)
        return b

    def card(title=None):
        f = QFrame()
        f.setObjectName("Card")
        lay = QVBoxLayout(f)
        lay.setContentsMargins(18, 16, 18, 18)
        lay.setSpacing(10)
        if title:
            lay.addWidget(label(title.upper(), "Section"))
        return f, lay

    class Job(QThread):
        ok = pyqtSignal(object)
        err = pyqtSignal(str)

        def __init__(self, fn):
            super().__init__()
            self.fn = fn

        def run(self):
            try:
                self.ok.emit(self.fn())
            except Coded7Error as ex:
                self.err.emit(str(ex))
            except MemoryError:
                self.err.emit("Not enough memory for this file.")
            except Exception as ex:  # noqa: BLE001
                self.err.emit(f"{type(ex).__name__}: {ex}")

    class DropZone(QFrame):
        picked = pyqtSignal(str)

        def __init__(self, title, hint, dialog_title, name_filter=""):
            super().__init__()
            self.setObjectName("Drop")
            self.setAcceptDrops(True)
            self.setCursor(Qt.CursorShape.PointingHandCursor)
            self.setMinimumHeight(150)
            self.dialog_title, self.name_filter = dialog_title, name_filter
            self.default = (title, hint)
            lay = QVBoxLayout(self)
            lay.setAlignment(Qt.AlignmentFlag.AlignCenter)
            self.thumb = QLabel()
            self.thumb.setAlignment(Qt.AlignmentFlag.AlignCenter)
            self.thumb.setStyleSheet("background: transparent;")
            self.icon = QLabel("⤓")
            self.icon.setStyleSheet(f"font-size: 26pt; color: {ACCENT}; background: transparent;")
            self.icon.setAlignment(Qt.AlignmentFlag.AlignCenter)
            self.title = QLabel(title)
            self.title.setStyleSheet("font-weight: 700; font-size: 11pt; background: transparent;")
            self.title.setAlignment(Qt.AlignmentFlag.AlignCenter)
            self.hint = QLabel(hint)
            self.hint.setObjectName("Small")
            self.hint.setAlignment(Qt.AlignmentFlag.AlignCenter)
            self.hint.setWordWrap(True)
            for wdg in (self.thumb, self.icon, self.title, self.hint):
                lay.addWidget(wdg)
            self.thumb.hide()

        def _hover(self, on):
            self.setProperty("hover", "true" if on else "false")
            self.style().unpolish(self)
            self.style().polish(self)

        def dragEnterEvent(self, e):
            if e.mimeData().hasUrls():
                e.acceptProposedAction()
                self._hover(True)

        def dragLeaveEvent(self, e):
            self._hover(False)

        def dropEvent(self, e):
            self._hover(False)
            urls = [u.toLocalFile() for u in e.mimeData().urls() if u.isLocalFile()]
            if urls:
                self.picked.emit(urls[0])

        def mousePressEvent(self, e):
            path, _ = QFileDialog.getOpenFileName(self, self.dialog_title, "", self.name_filter)
            if path:
                self.picked.emit(path)

        def show_file(self, title, hint, pixmap=None):
            self.title.setText(title)
            self.hint.setText(hint)
            if pixmap is not None:
                self.thumb.setPixmap(pixmap)
                self.thumb.show()
                self.icon.hide()
            else:
                self.thumb.hide()
                self.icon.show()

        def reset(self):
            self.show_file(*self.default)

    class KeyBox(QWidget):
        """Password (+ optional confirm, strength meter and generator) and keyfile picker."""

        def __init__(self, win, creating):
            super().__init__()
            self.win, self.creating = win, creating
            self.keyfile, self.keyname = None, ""
            g = QGridLayout(self)
            g.setContentsMargins(0, 0, 0, 0)
            g.setHorizontalSpacing(10)
            g.setVerticalSpacing(8)
            self.pw = QLineEdit()
            self.pw.setEchoMode(QLineEdit.EchoMode.Password)
            self.pw.setPlaceholderText("Optional" if creating else "Leave empty if none was set")
            g.addWidget(label("Password"), 0, 0)
            g.addWidget(self.pw, 0, 1)
            self.show_cb = QCheckBox("Show")
            self.show_cb.toggled.connect(self._toggle)
            g.addWidget(self.show_cb, 0, 2)
            row = 1
            if creating:
                self.confirm = QLineEdit()
                self.confirm.setEchoMode(QLineEdit.EchoMode.Password)
                self.confirm.setPlaceholderText("Repeat the password")
                self.confirm.setEnabled(False)
                g.addWidget(label("Confirm"), 1, 0)
                g.addWidget(self.confirm, 1, 1)
                g.addWidget(button("Generate", slot=self.generate, tip="Create a strong random password and copy it"), 1, 2)
                meter_row = QHBoxLayout()
                self.meter = QProgressBar()
                self.meter.setRange(0, 120)
                self.meter.setTextVisible(False)
                self.meter_lbl = label("", "Small")
                self.meter_lbl.setMinimumWidth(170)
                meter_row.addWidget(self.meter, 1)
                meter_row.addWidget(self.meter_lbl)
                g.addLayout(meter_row, 2, 1, 1, 2)
                self.pw.textChanged.connect(self.update_meter)
                self.update_meter()
                row = 3
            kf_row = QHBoxLayout()
            self.kf_lbl = label("None", "Muted")
            kf_row.addWidget(self.kf_lbl, 1)
            kf_row.addWidget(button("Choose…", slot=self.pick_keyfile,
                                    tip="Any file can act as a second key. The exact same file is needed to decrypt."))
            self.kf_clear = button("Remove", slot=self.clear_keyfile)
            self.kf_clear.setEnabled(False)
            kf_row.addWidget(self.kf_clear)
            g.addWidget(label("Keyfile"), row, 0)
            g.addLayout(kf_row, row, 1, 1, 2)
            g.setColumnStretch(1, 1)

        def _toggle(self, on):
            mode = QLineEdit.EchoMode.Normal if on else QLineEdit.EchoMode.Password
            self.pw.setEchoMode(mode)
            if self.creating:
                self.confirm.setEchoMode(mode)

        def update_meter(self):
            pw = self.pw.text()
            if not pw:
                self.confirm.clear()
            self.confirm.setEnabled(bool(pw))
            bits = password_bits(pw)
            col = "#ef4444" if bits < 50 else "#f59e0b" if bits < 80 else "#22c55e"
            self.meter.setValue(int(min(bits, 120)))
            self.meter.setStyleSheet(f"QProgressBar::chunk {{ background: {col}; border-radius: 3px; }}")
            if not pw:
                self.meter_lbl.setText("No password. Anyone with CODED7 can open it.")
            else:
                word = "Very weak" if bits < 40 else "Weak" if bits < 60 else "Fair" if bits < 80 else "Strong" if bits < 110 else "Excellent"
                self.meter_lbl.setText(f"{word} · ~{int(bits)} bits")

        def generate(self):
            pw = generate_password()
            self.pw.setText(pw)
            self.confirm.setText(pw)
            self.show_cb.setChecked(True)
            cb = QGuiApplication.clipboard()
            cb.setText(pw)
            QTimer.singleShot(45_000, lambda: cb.text() == pw and cb.clear())
            self.win.status("Generated password copied to clipboard (cleared after 45 s). Store it somewhere safe.")

        def pick_keyfile(self):
            path, _ = QFileDialog.getOpenFileName(self, "Choose keyfile")
            if path:
                try:
                    self.keyfile = _read_keyfile(path)
                except (OSError, Coded7Error) as ex:
                    QMessageBox.warning(self, "Keyfile", str(ex))
                    return
                self.keyname = os.path.basename(path)
                self.kf_lbl.setText(f"{self.keyname}  ·  {_fmt_size(len(self.keyfile))}")
                self.kf_lbl.setObjectName("Ok")
                self.kf_lbl.setStyleSheet("color: #4ade80;")
                self.kf_clear.setEnabled(True)

        def clear_keyfile(self):
            self.keyfile, self.keyname = None, ""
            self.kf_lbl.setText("None")
            self.kf_lbl.setStyleSheet("")
            self.kf_clear.setEnabled(False)

        def password(self):
            """The password (may be empty), or None if the confirmation does not match."""
            pw = self.pw.text()
            if self.creating and pw and pw != self.confirm.text():
                self.win.error("The passwords do not match.")
                self.confirm.setFocus()
                return None
            return pw

        def clear(self):
            self.pw.clear()
            if self.creating:
                self.confirm.clear()
            self.show_cb.setChecked(False)
            self.clear_keyfile()

    class Page(QWidget):
        def __init__(self, title, subtitle):
            super().__init__()
            self.setObjectName("Page")
            self.root = QVBoxLayout(self)
            self.root.setContentsMargins(32, 26, 32, 22)
            self.root.setSpacing(16)
            head = QHBoxLayout()
            tbox = QVBoxLayout()
            tbox.setSpacing(2)
            tbox.addWidget(label(title, "H1"))
            tbox.addWidget(label(subtitle, "Muted"))
            head.addLayout(tbox, 1)
            self.clear_btn = button("Clear")
            head.addWidget(self.clear_btn, 0, Qt.AlignmentFlag.AlignTop)
            self.root.addLayout(head)
            self.body = QHBoxLayout()
            self.body.setSpacing(16)
            self.root.addLayout(self.body, 1)

    class MainWindow(QMainWindow):
        def __init__(self):
            super().__init__()
            self.setWindowTitle("CODED7")
            self.resize(1200, 780)
            self.setMinimumSize(1020, 680)
            self.job = None
            central = QWidget()
            outer = QHBoxLayout(central)
            outer.setContentsMargins(0, 0, 0, 0)
            outer.setSpacing(0)
            self.setCentralWidget(central)

            # sidebar
            side = QFrame()
            side.setObjectName("Sidebar")
            side.setFixedWidth(210)
            sl = QVBoxLayout(side)
            sl.setContentsMargins(14, 20, 14, 16)
            sl.setSpacing(4)
            brand = QHBoxLayout()
            logo = QLabel()
            logo.setPixmap(pil_to_pixmap(make_icon(128), 38))
            logo.setStyleSheet("background: transparent;")
            brand.addWidget(logo)
            bt = QVBoxLayout()
            bt.setSpacing(0)
            bt.addWidget(label("CODED7", "Brand"))
            bt.addWidget(label("Image encryption", "BrandSub"))
            brand.addLayout(bt, 1)
            sl.addLayout(brand)
            sl.addSpacing(22)
            self.nav = QButtonGroup(self)
            self.stack = QStackedWidget()
            self.enc = self.build_encrypt()
            self.dec = self.build_decrypt()
            for i, (text, page) in enumerate((("Encrypt", self.enc), ("Decrypt", self.dec))):
                b = button(text, "Nav")
                b.setCheckable(True)
                self.nav.addButton(b, i)
                sl.addWidget(b)
                self.stack.addWidget(page)
            self.nav.button(0).setChecked(True)
            self.nav.idClicked.connect(self.stack.setCurrentIndex)
            sl.addStretch(1)
            sl.addWidget(button("About", "Nav", self.about))
            sl.addWidget(label(f"v{APP_VERSION}", "Small"))
            outer.addWidget(side)
            outer.addWidget(self.stack, 1)

            # status bar
            self.busy_bar = QProgressBar()
            self.busy_bar.setRange(0, 0)
            self.busy_bar.setFixedWidth(160)
            self.busy_bar.hide()
            self.statusBar().addPermanentWidget(self.busy_bar)
            self.status("Ready.")
            QShortcut(QKeySequence("Ctrl+Return"), self, activated=self.primary)

        # ---------- helpers ----------
        def status(self, msg):
            self.statusBar().showMessage(msg)

        def error(self, msg):
            self.status(msg)
            QMessageBox.warning(self, "CODED7", msg)

        def primary(self):
            (self.do_encrypt if self.stack.currentIndex() == 0 else self.do_decrypt)()

        def run(self, msg, fn, done, buttons, on_error=None):
            if self.job is not None:
                return
            for b in buttons:
                b.setEnabled(False)
            self.busy_bar.show()
            self.status(msg)
            QApplication.setOverrideCursor(Qt.CursorShape.BusyCursor)
            job = Job(fn)

            def finish():
                QApplication.restoreOverrideCursor()
                self.busy_bar.hide()
                for b in buttons:
                    b.setEnabled(True)
                self.job = None

            outcome = {}
            job.ok.connect(lambda res: outcome.update(ok=res))
            job.err.connect(lambda m: outcome.update(err=m))

            def on_finished():          # thread has fully stopped - safe to release it now
                finish()
                if "ok" in outcome:
                    done(outcome["ok"])
                else:
                    (on_error or self.error)(outcome.get("err", "Unknown error."))

            job.finished.connect(on_finished)
            self.job = job
            job.start()

        # ---------- encrypt page ----------
        def build_encrypt(self):
            pg = Page("Encrypt", "Hide text or any file inside an image. Only CODED7 with the right password can open it.")
            left = QVBoxLayout()
            left.setSpacing(16)

            c, lay = card("Content")
            seg = QHBoxLayout()
            seg.setSpacing(6)
            self.enc_mode = QButtonGroup(self)
            for i, t in enumerate(("Text", "File")):
                b = button(t, "Seg")
                b.setCheckable(True)
                self.enc_mode.addButton(b, i)
                seg.addWidget(b)
            seg.addStretch(1)
            self.enc_count = label("", "Small")
            seg.addWidget(self.enc_count)
            lay.addLayout(seg)
            self.enc_stack = QStackedWidget()
            self.enc_text = QPlainTextEdit()
            self.enc_text.setPlaceholderText("Type or paste the text you want to protect…")
            self.enc_text.textChanged.connect(self.update_count)
            self.enc_drop = DropZone("Drop a file here", "or click to browse · documents, photos, archives — any file type",
                                     "Choose a file to encrypt")
            self.enc_drop.picked.connect(self.set_enc_file)
            self.enc_file = None
            self.enc_stack.addWidget(self.enc_text)
            self.enc_stack.addWidget(self.enc_drop)
            lay.addWidget(self.enc_stack, 1)
            self.enc_mode.idClicked.connect(lambda i: (self.enc_stack.setCurrentIndex(i), self.update_count()))
            self.enc_mode.button(0).setChecked(True)
            left.addWidget(c, 1)

            c, lay = card("Protection")
            self.enc_keys = KeyBox(self, creating=True)
            lay.addWidget(self.enc_keys)
            left.addWidget(c)

            c, lay = card("Output")
            row = QHBoxLayout()
            row.addWidget(label("Image style"))
            self.style_box = QComboBox()
            for key, (name, _) in ART_STYLES.items():
                self.style_box.addItem(name, key)
            self.style_box.currentIndexChanged.connect(self.update_style_preview)
            row.addWidget(self.style_box)
            row.addStretch(1)
            self.enc_btn = button("Encrypt and save…", "Primary", self.do_encrypt)
            row.addWidget(self.enc_btn)
            lay.addLayout(row)
            left.addWidget(c)
            pg.body.addLayout(left, 1)

            c, lay = card("Result")
            c.setFixedWidth(360)
            self.enc_preview = QLabel()
            self.enc_preview.setObjectName("Preview")
            self.enc_preview.setAlignment(Qt.AlignmentFlag.AlignCenter)
            self.enc_preview.setFixedSize(322, 322)
            lay.addWidget(self.enc_preview)
            self.enc_info = label("", "Muted", wrap=True)
            lay.addWidget(self.enc_info)
            r = QHBoxLayout()
            self.enc_open = button("Show in folder", slot=lambda: self.open_folder(self.enc_saved))
            self.enc_copy = button("Copy path", slot=lambda: QGuiApplication.clipboard().setText(self.enc_saved or ""))
            for b in (self.enc_open, self.enc_copy):
                b.setEnabled(False)
                r.addWidget(b)
            lay.addLayout(r)
            lay.addStretch(1)
            tip = label("Send encrypted images as a file or document. Messaging apps that compress photos "
                        "(WhatsApp, Instagram, …) destroy the hidden data.", "Small", wrap=True)
            lay.addWidget(tip)
            pg.body.addWidget(c)
            self.enc_saved = None
            pg.clear_btn.clicked.connect(self.clear_encrypt)
            QTimer.singleShot(0, self.update_style_preview)
            return pg

        def update_count(self):
            if self.enc_stack.currentIndex() == 0:
                t = self.enc_text.toPlainText()
                self.enc_count.setText(f"{len(t):,} characters · {_fmt_size(len(t.encode()))}" if t else "")
            else:
                self.enc_count.setText(_fmt_size(os.path.getsize(self.enc_file)) if self.enc_file else "")

        def set_enc_file(self, path):
            if not os.path.isfile(path):
                return self.error("That is not a file.")
            self.enc_file = path
            pm = None
            try:
                im = Image.open(path)
                im.load()
                pm = pil_to_pixmap(im, 90)
            except Exception:  # noqa: BLE001
                pass
            self.enc_drop.show_file(os.path.basename(path), f"{_fmt_size(os.path.getsize(path))} · click or drop to replace", pm)
            self.update_count()

        def update_style_preview(self):
            if self.enc_saved:
                return
            key = self.style_box.currentData()
            self.enc_preview.setPixmap(pil_to_pixmap(ART_STYLES[key][1](322, 322), 320))
            self.enc_info.setText(f"Preview of the “{ART_STYLES[key][0]}” style. Every image is generated fresh and unique.")

        def do_encrypt(self):
            if self.enc_stack.currentIndex() == 0:
                text = self.enc_text.toPlainText()
                if not text.strip():
                    return self.error("Enter some text to encrypt.")
                kind, name, data, what = KIND_TEXT, "", text.encode("utf-8"), f"{len(text):,} characters of text"
            else:
                if not self.enc_file:
                    return self.error("Choose a file to encrypt.")
                kind, name = KIND_FILE, os.path.basename(self.enc_file)
                data, what = None, name
            pw = self.enc_keys.password()
            if pw is None:
                return
            out, _ = QFileDialog.getSaveFileName(self, "Save encrypted image", "encrypted.png", "PNG image (*.png)")
            if not out:
                return
            if not out.lower().endswith(".png"):
                out += ".png"
            kf, style, src = self.enc_keys.keyfile, self.style_box.currentData(), self.enc_file

            def work():
                payload = data
                if payload is None:
                    with open(src, "rb") as fh:
                        payload = fh.read()
                img = encode(kind, name, payload, pw, kf, style)
                img.save(out, "PNG")
                return img, out, len(payload)

            def done(res):
                img, path, n = res
                self.enc_saved = path
                self.enc_preview.setPixmap(pil_to_pixmap(img, 320))
                self.enc_info.setText(f"<b>{os.path.basename(path)}</b><br>{img.size[0]} × {img.size[1]} px · "
                                      f"{_fmt_size(os.path.getsize(path))}<br>Contains: {what} ({_fmt_size(n)})"
                                      + (f"<br>Keyfile required: {self.enc_keys.keyname}" if kf else ""))
                self.enc_open.setEnabled(True)
                self.enc_copy.setEnabled(True)
                self.status(f"Encrypted and saved to {path}")

            self.enc_saved = None
            self.run("Encrypting…", work, done, [self.enc_btn])

        def clear_encrypt(self):
            self.enc_text.clear()
            self.enc_file = None
            self.enc_drop.reset()
            self.enc_keys.clear()
            self.enc_saved = None
            for b in (self.enc_open, self.enc_copy):
                b.setEnabled(False)
            self.update_style_preview()
            self.update_count()
            self.status("Cleared.")

        def open_folder(self, path):
            if path:
                QDesktopServices.openUrl(QUrl.fromLocalFile(os.path.dirname(path)))

        # ---------- decrypt page ----------
        def build_decrypt(self):
            pg = Page("Decrypt", "Open an image created by CODED7 to reveal the text or file inside.")
            left = QVBoxLayout()
            left.setSpacing(16)
            c, lay = card("Encrypted image")
            self.dec_drop = DropZone("Drop the encrypted image here", "or click to browse · PNG files created by CODED7",
                                     "Choose an encrypted image", "Images (*.png *.PNG);;All files (*)")
            self.dec_drop.picked.connect(self.set_dec_image)
            self.dec_path = None
            lay.addWidget(self.dec_drop, 1)
            left.addWidget(c, 1)
            c, lay = card("Key")
            self.dec_keys = KeyBox(self, creating=False)
            lay.addWidget(self.dec_keys)
            r = QHBoxLayout()
            r.addStretch(1)
            self.dec_btn = button("Decrypt", "Primary", self.do_decrypt)
            r.addWidget(self.dec_btn)
            lay.addLayout(r)
            left.addWidget(c)
            pg.body.addLayout(left, 1)

            c, lay = card("Result")
            c.setFixedWidth(420)
            self.dec_stack = QStackedWidget()
            empty = label("The decrypted text or file will appear here.", "Muted", wrap=True)
            empty.setAlignment(Qt.AlignmentFlag.AlignCenter)
            self.dec_stack.addWidget(empty)
            # text result
            tw = QWidget()
            tl = QVBoxLayout(tw)
            tl.setContentsMargins(0, 0, 0, 0)
            self.dec_text = QPlainTextEdit()
            self.dec_text.setReadOnly(True)
            tl.addWidget(self.dec_text, 1)
            tr = QHBoxLayout()
            self.dec_text_info = label("", "Small")
            tr.addWidget(self.dec_text_info, 1)
            tr.addWidget(button("Copy", slot=lambda: (QGuiApplication.clipboard().setText(self.dec_text.toPlainText()),
                                                      self.status("Text copied to clipboard."))))
            tr.addWidget(button("Save as…", slot=self.save_dec_text))
            tl.addLayout(tr)
            self.dec_stack.addWidget(tw)
            # file result
            fw = QWidget()
            fl = QVBoxLayout(fw)
            fl.setContentsMargins(0, 0, 0, 0)
            self.dec_file_prev = QLabel()
            self.dec_file_prev.setObjectName("Preview")
            self.dec_file_prev.setAlignment(Qt.AlignmentFlag.AlignCenter)
            self.dec_file_prev.setMinimumHeight(260)
            fl.addWidget(self.dec_file_prev, 1)
            self.dec_file_info = label("", wrap=True)
            fl.addWidget(self.dec_file_info)
            fr = QHBoxLayout()
            fr.addStretch(1)
            self.dec_save_btn = button("Save file…", "Primary", self.save_dec_file)
            fr.addWidget(self.dec_save_btn)
            fl.addLayout(fr)
            self.dec_stack.addWidget(fw)
            self.console = QPlainTextEdit()
            self.console.setObjectName("Console")
            self.console.setReadOnly(True)
            self.console.setMaximumBlockCount(500)
            self.console.setLineWrapMode(QPlainTextEdit.LineWrapMode.WidgetWidth)
            self.console.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
            self.console.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
            self.dec_stack.addWidget(self.console)
            self.fx_timer = QTimer(self)
            self.fx_timer.timeout.connect(self.fx_tick)
            self.scr_timer = QTimer(self)
            self.scr_timer.timeout.connect(self.scramble_tick)
            lay.addWidget(self.dec_stack, 1)
            pg.body.addWidget(c)
            self.dec_payload = None
            pg.clear_btn.clicked.connect(self.clear_decrypt)
            return pg

        def set_dec_image(self, path):
            try:
                im = Image.open(path)
                im.load()
            except Exception:  # noqa: BLE001
                return self.error("That file is not an image.")
            self.dec_path = path
            self.dec_size = im.size
            self.dec_drop.show_file(os.path.basename(path),
                                    f"{im.size[0]} × {im.size[1]} px · {_fmt_size(os.path.getsize(path))} · click or drop to replace",
                                    pil_to_pixmap(im, 220))
            if im.format != "PNG":
                self.status(f"Warning: this is a {im.format} file. CODED7 images are PNG; converted copies usually can't be decrypted.")

        def do_decrypt(self):
            if not self.dec_path:
                return self.error("Choose the encrypted image first.")
            pw = self.dec_keys.password()
            if pw is None:
                return
            path, kf = self.dec_path, self.dec_keys.keyfile

            def work():
                return decode(Image.open(path), pw, kf)

            def done(res):
                kind, name, data = res
                self.dec_payload = (kind, name, data)
                if kind == KIND_TEXT:
                    t = data.decode("utf-8", errors="replace")
                    self.dec_text_info.setText(f"{len(t):,} characters")
                    self.dec_stack.setCurrentIndex(1)
                    self.scramble(t, self.dec_text.setPlainText)
                else:
                    pm = None
                    try:
                        inner = Image.open(io.BytesIO(data))
                        inner.load()
                        pm = pil_to_pixmap(inner, 380)
                    except Exception:  # noqa: BLE001
                        pass
                    if pm:
                        self.dec_file_prev.setPixmap(pm)
                    else:
                        self.dec_file_prev.setText("📄")
                        self.dec_file_prev.setStyleSheet("font-size: 48pt;")
                    size_txt = _fmt_size(len(data))
                    self.dec_stack.setCurrentIndex(2)
                    self.scramble(_safe_name(name),
                                  lambda v: self.dec_file_info.setText(f"<b>{html.escape(v)}</b><br>{size_txt}"))
                self.status("Decrypted successfully.")

            self.fx_start(self.dec_size, bool(pw), bool(kf))
            self.run("Decrypting…", work, lambda res: self.fx_finish("ok", (res, done)), [self.dec_btn],
                     on_error=lambda m: self.fx_finish("err", m))

        # ---------- decrypt animation ----------
        def fx_line(self, text, color="#3ddc84", bold=False):
            w = "font-weight:700;" if bold else ""
            self.console.appendHtml(f'<span style="color:{color};{w}white-space:pre">{html.escape(text)}</span>')

        def fx_start(self, size, has_pw, has_kf):
            self.scr_timer.stop()
            self.console.clear()
            self.dec_stack.setCurrentIndex(3)
            w, h = size
            self.fx = {"t0": time.monotonic(), "tick": 0, "addr": random.randrange(0, 1 << 20) * 16,
                       "done": None, "post": None, "hold": 0}
            self.fx_pre = [
                f"> open image ............ {w}x{h} RGB",
                f"> scan channels ......... {w * h * 3:,}",
                "> keyed permutation ..... feistel x6",
                "> read header ........... salt[32] len[4]",
                "> key material .......... " + ("password + " if has_pw else "") + ("keyfile + " if has_kf else "") + "master",
                "> argon2id .............. m=128MiB t=4 p=4",
            ]
            self.fx_line(f"coded7 v{APP_VERSION} // decrypt session {os.urandom(4).hex()}", "#8b93a1")
            self.fx_timer.start(40)

        def fx_finish(self, kind, payload):
            self.fx["done"] = (kind, payload)
            self.dec_btn.setEnabled(False)

        def fx_tick(self):
            fx = self.fx
            fx["tick"] += 1
            if fx["post"] is None:
                b = os.urandom(16)
                hexs = " ".join(f"{x:02x}" for x in b[:8]) + "  " + " ".join(f"{x:02x}" for x in b[8:])
                asc = "".join(chr(x) if 33 <= x < 127 else "." for x in b)
                self.console.appendHtml(
                    f'<span style="white-space:pre"><span style="color:#2f6b47">{fx["addr"]:08x}</span>  '
                    f'<span style="color:#3ddc84">{hexs}</span>  <span style="color:#1f8f55">{html.escape(asc)}</span></span>')
                fx["addr"] += 16
                if fx["tick"] % 6 == 0 and self.fx_pre:
                    self.fx_line(self.fx_pre.pop(0), "#e6ffe9", bold=True)
                if fx["done"] and not self.fx_pre and time.monotonic() - fx["t0"] > 1.6:
                    kind, _ = fx["done"]
                    if kind == "ok":
                        fx["post"] = ["> aes-256-gcm ........... tag OK", "> chacha20-poly1305 ..... tag OK",
                                      "> inflate payload ....... OK", "", "ACCESS GRANTED"]
                    else:
                        fx["post"] = ["> aes-256-gcm ........... tag MISMATCH", "", "ACCESS DENIED"]
            elif fx["post"]:
                if fx["tick"] % 3 == 0:
                    line = fx["post"].pop(0)
                    if line.startswith("ACCESS"):
                        ok = line == "ACCESS GRANTED"
                        self.console.appendHtml(
                            f'<span style="color:{"#4ade80" if ok else "#ff5c5c"};font-size:20pt;font-weight:800;'
                            f'letter-spacing:4px">{line}</span>')
                    else:
                        self.fx_line(line, "#ff5c5c" if "MISMATCH" in line else "#e6ffe9", bold=True)
            else:
                fx["hold"] += 1
                if fx["hold"] >= 18:
                    self.fx_timer.stop()
                    self.dec_btn.setEnabled(True)
                    kind, payload = fx["done"]
                    if kind == "ok":
                        res, show = payload
                        show(res)
                    else:
                        self.status(payload)
                        self.fx_line("")
                        self.fx_line(payload, "#ff9b9b")

        def scramble(self, final, setter):
            glyphs = "ABCDEF0123456789#$%&@*+=<>/\\|{}[]?!"
            limit = min(len(final), 2500)
            self.scr = {"final": final, "setter": setter, "pos": 0, "limit": limit,
                        "step": max(1, limit // 45), "glyphs": glyphs}
            self.scr_timer.start(30)

        def scramble_tick(self):
            sc = self.scr
            sc["pos"] += sc["step"]
            if sc["pos"] >= sc["limit"]:
                self.scr_timer.stop()
                sc["setter"](sc["final"])
                return
            f, g = sc["final"], sc["glyphs"]
            tail = "".join(c if c.isspace() else random.choice(g) for c in f[sc["pos"]:sc["limit"]])
            sc["setter"](f[:sc["pos"]] + tail)

        def save_dec_text(self):
            path, _ = QFileDialog.getSaveFileName(self, "Save text", "decrypted.txt", "Text (*.txt);;All files (*)")
            if path:
                with open(path, "w", encoding="utf-8") as fh:
                    fh.write(self.dec_text.toPlainText())
                self.status(f"Saved to {path}")

        def save_dec_file(self):
            if not self.dec_payload:
                return
            _, name, data = self.dec_payload
            path, _ = QFileDialog.getSaveFileName(self, "Save decrypted file", _safe_name(name))
            if path:
                with open(path, "wb") as fh:
                    fh.write(data)
                self.status(f"Saved to {path}")

        def clear_decrypt(self):
            self.dec_path = None
            self.dec_payload = None
            self.dec_drop.reset()
            self.dec_keys.clear()
            self.dec_text.clear()
            self.dec_file_prev.clear()
            self.dec_stack.setCurrentIndex(0)
            self.status("Cleared.")

        def about(self):
            QMessageBox.about(self, "About CODED7", f"""
                <h3>CODED7 {APP_VERSION}</h3>
                <p>Encrypts text and files into ordinary-looking PNG images.</p>
                <p><b>Key derivation:</b> Argon2id — 128 MiB, 4 passes, 4 lanes, 256-bit random salt<br>
                <b>Encryption:</b> ChaCha20-Poly1305 inside AES-256-GCM (independent 256-bit keys)<br>
                <b>Second factor:</b> optional keyfile (SHA-512)<br>
                <b>Embedding:</b> 2 low bits per colour channel, keyed Feistel permutation,
                random fill and size padding</p>
                <p>Images are interchangeable with the CODED7 Android app.<br>
                A forgotten password cannot be recovered.</p>""")

        def closeEvent(self, e):
            if self.job is not None:
                self.job.wait()
            e.accept()

    app = QApplication.instance() or QApplication(sys.argv)
    app.setApplicationName("CODED7")
    app.setDesktopFileName("coded7")
    app.setStyle("Fusion")
    app.setStyleSheet(QSS)
    app.setWindowIcon(QIcon(pil_to_pixmap(make_icon(256), 256)))
    win = MainWindow()
    win.show()
    return app.exec()


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