aboutsummaryrefslogtreecommitdiffstats
path: root/bin/udt-accent
blob: 70557d8178f2ec009b246bcca3f8f1a8e4b087e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-only
# udt-accent: pick the scheme accent matching a wallpaper.
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
# Licensed under the GNU General Public License v2 only.
"""Extract a wallpaper's signature color and snap it to one of the scheme's accents.

Usage: udt-accent <wallpaper-path>
       udt-accent --selftest
       udt-accent --help

The extraction reads the image's pixels itself rather than running `wal -i`,
because `wal -i` rewrites the whole ~/.cache/wal directory (which this no
longer writes to, but pywal still would) including the terminal's ANSI colors.
See the design spec for why that matters.
"""

import getpass
import json
import math
import os
import re
import subprocess
import sys
import tempfile
from pathlib import Path

# The colour tables are generated: udt-palette renders them from
# palette/<scheme>.conf and palette/roles-<scheme>.conf, so the accents this
# snaps to follow whatever scheme is selected. Regenerate with ./install.sh.
sys.path.insert(0, str(Path(__file__).resolve().parent))
from udt_colors import ACCENTS, FALLBACK, PALETTE, SCHEME  # noqa: E402

MIN_CHROMA = 10.0
# A wallpaper's pick below this is a tint, not a colour that stands out: over
# 314 real wallpapers, near-monochrome images landed at 19-24 and every pick
# that read as the image's accent at 33 or more.
SIGNATURE_MIN_CHROMA = 25.0
# The share of pixels, by salience, that votes on the accent's hue.
SALIENT_SHARE = 0.02

CACHE = Path.home() / ".cache" / "udt"
OUTPUT = CACHE / "udt-accent.rasi"
BORDER_OUTPUT = CACHE / "udt-border.lua"
# hyprlock cannot read the Lua border table, so the same three hues are also
# written as a hyprlang variable the lock config sources. See write_hyprlock.
HYPRLOCK_BORDER_OUTPUT = CACHE / "hyprlock-border.conf"
SUBLIME = (Path.home() / ".config" / "sublime-text" / "Packages" / "User"
           / "udt.sublime-color-scheme")
QML_OUTPUT = CACHE / "udt-palette.qml"
# Generated by udt-palette with the scheme's accent and rewritten here with the
# wallpaper's. Both already go stale on a wallpaper change, GRUB's background
# and homepage's staged wallpaper, so following the accent costs no extra step.
REPO = Path(__file__).resolve().parent.parent
GRUB_THEME = REPO.parent / "grub-theme-udt" / "theme.txt"
HOMEPAGE_CSS = REPO / "templates" / "homepage" / "custom.css"

# The installed rofi palette, itself generated by udt-palette. Read rather than
# duplicated so the QML singleton carries exactly the colours rofi uses, under
# the same names.
PALETTE_RASI = Path.home() / ".config" / "rofi" / "udt" / "palette.rasi"
# pywalfox hardcodes <cache>/wal/colors.json and honours only XDG_CACHE_HOME,
# which would move every cache, so this one file is written where it looks.
# install.sh symlinks ~/.cache/wal/colors.json here, so the real file lives
# with the rest of the palette and ~/.cache/wal holds nothing but that link.
COLORS_JSON = CACHE / "colors.json"
# FF Ultima's new tab background slots. darknix.png is the one udt fills.
FIREFOX_WALLS = "chrome/theme/color-schemes/walls"
# Gaussian radius in px at 1920 wide, for the new tab background.
FIREFOX_BLUR = 24

# The SDDM theme's live palette. ~/.cache is 0700 and unreachable to the sddm
# user, ~/.local/share is 0755, so the file has to live here. Root symlinks
# /usr/share/sddm/themes/udt/theme.conf.user to it. See the sddm-theme-udt spec.
LIBEXEC = Path.home() / ".local" / "share" / "udt"
SDDM_OUTPUT = LIBEXEC / "sddm-theme.conf"

# The keys the theme asks for. The names are the same Catppuccin-compat names
# palette.rasi and udt-palette.qml use, so one palette has one vocabulary.
SDDM_KEYS = ["base", "mantle", "crust", "surface0", "surface1", "surface2",
             "text", "subtext0", "subtext1", "overlay0", "overlay1", "overlay2",
             "red", "yellow", "green", "teal", "blue", "lavender"]

# The SDDM panel's power icons. The greeter runs as the sddm user and cannot
# read the login user's dconf, so udt-accent resolves the selected icon theme
# to absolute paths and bakes them into the INI. An unresolved key stays empty
# and the theme draws its bundled SVG instead.
ICON_SCHEMA = "org.gnome.desktop.interface"
ICON_KEY = "icon-theme"
ICON_DIRS = [Path.home() / ".local" / "share" / "icons",
             Path("/usr/share/icons")]
POWER_ICONS = {
    "powerIcon": ["system-shutdown"],
    "rebootIcon": ["system-reboot"],
    "suspendIcon": ["system-suspend"],
    "hibernateIcon": ["system-hibernate", "system-suspend-hibernate"],
}

# The login avatar hyprlock and the rofi powermenu draw, handed to the greeter
# so the login screen shows the same file instead of the AccountsService icon.
# The sddm user reaches it through the 0711 home, so it has to stay 0644.
AVATAR = Path.home() / ".user-icon.jpg"

# wallp's config and state: which output each logical screen (H, V) is, and
# the wallpaper on it. Read so the greeter can show each monitor its own
# wallpaper, as the desktop does.
WALLP = Path.home() / ".config" / "wallp"


def write_atomic(path, content, mode=None, dir_mode=None):
    """Write a file atomically, so no reader ever sees it half-written.

    Every generated file is watched by something: rofi rereads on launch,
    quickshell watches with a FileView. A torn read shows up as a theme that
    briefly loses its colours.

    `mode` is applied to the temp file before the rename, so a reader never
    opens a file that is briefly unreadable. `dir_mode` does the same for the
    parent directory, which umask would otherwise mask. Both default to the
    process defaults (mkstemp 0600, umask-derived directory).
    """
    path.parent.mkdir(parents=True, exist_ok=True)
    if dir_mode is not None:
        # mkdir masks its mode through umask, so set it explicitly.
        os.chmod(path.parent, dir_mode)
    fd, tmp = tempfile.mkstemp(dir=str(path.parent), suffix=".tmp")
    try:
        with os.fdopen(fd, "w") as handle:
            handle.write(content)
        if mode is not None:
            os.chmod(tmp, mode)
        os.replace(tmp, path)
    except BaseException:
        if os.path.exists(tmp):
            os.unlink(tmp)
        raise


def _to_lab(hexval):
    """Convert #rrggbb to CIELAB. sRGB D65, the standard conversion."""
    r, g, b = (int(hexval[i:i + 2], 16) / 255 for i in (1, 3, 5))

    def linear(c):
        return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4

    r, g, b = linear(r), linear(g), linear(b)

    x = (0.4124 * r + 0.3576 * g + 0.1805 * b) / 0.95047
    y = (0.2126 * r + 0.7152 * g + 0.0722 * b)
    z = (0.0193 * r + 0.1192 * g + 0.9505 * b) / 1.08883

    def f(t):
        return t ** (1 / 3) if t > 0.008856 else 7.787 * t + 16 / 116

    fx, fy, fz = f(x), f(y), f(z)
    return (116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz))


def _hue(hexval):
    """Perceptual hue angle in radians."""
    _, a, b = _to_lab(hexval)
    return math.atan2(b, a)


def _chroma(hexval):
    """Distance from the neutral axis. Near-greys sit close to zero."""
    _, a, b = _to_lab(hexval)
    return math.hypot(a, b)


def snap(hexval):
    """Return the name of the nearest candidate accent by perceptual hue."""
    if _chroma(hexval) < MIN_CHROMA:
        return FALLBACK

    target = _hue(hexval)

    def distance(name):
        delta = abs(_hue(ACCENTS[name]) - target)
        return min(delta, 2 * math.pi - delta)  # hue is circular

    return min(ACCENTS, key=distance)


def signature_color(image):
    """Return the colour that stands out most in the image, or None for a grey one.

    A pixel's salience is its chroma times its distance from the image's mean
    colour, so it has to be both vivid and unlike the rest of the image: a
    small violet motif on a frame full of skin wins over the skin. The most
    salient pixels vote by hue, each neighbouring hue band adding to the vote
    so violet and purple do not split it, and the most vivid pixel in the
    winning band is the result.

    This replaced pywal's colorz backend, whose cluster means averaged a
    small vivid element into its surroundings, whose random seeds let one
    wallpaper snap differently on two runs, and which calls sys.exit() on
    some images. Reading pixels writes nothing, so the pywal cache (and so
    the terminal) stays untouched.
    """
    from PIL import Image

    with Image.open(image) as im:
        im = im.convert("RGB")
        im.thumbnail((256, 256))
        raw = im.tobytes()
    pixels = [raw[i:i + 3].hex() for i in range(0, len(raw), 3)]
    lab = {p: _to_lab("#" + p) for p in set(pixels)}

    mean_a = sum(lab[p][1] for p in pixels) / len(pixels)
    mean_b = sum(lab[p][2] for p in pixels) / len(pixels)

    def chroma(p):
        return math.hypot(lab[p][1], lab[p][2])

    def salience(p):
        return chroma(p) * math.hypot(lab[p][1] - mean_a, lab[p][2] - mean_b)

    bands = 36

    def band(p):
        angle = math.atan2(lab[p][2], lab[p][1]) % (2 * math.pi)
        return int(angle / (2 * math.pi) * bands) % bands

    salient = sorted(pixels, key=salience, reverse=True)
    salient = salient[:max(1, int(len(salient) * SALIENT_SHARE))]
    votes = [0.0] * bands
    for p in salient:
        votes[band(p)] += chroma(p)
    smoothed = [votes[i - 1] + votes[i] + votes[(i + 1) % bands]
                for i in range(bands)]
    peak = max(range(bands), key=smoothed.__getitem__)

    # The same three bands the vote summed: the peak itself may be empty.
    near = ((peak - 1) % bands, peak, (peak + 1) % bands)
    best = max((p for p in salient if band(p) in near), key=chroma)
    return "#" + best if chroma(best) >= SIGNATURE_MIN_CHROMA else None


def write_accent(name):
    """Write the accent rasi file atomically."""
    hexval = ACCENTS[name]
    content = (
        "/* Generated by udt-accent. Do not edit. */\n"
        f"* {{ accent: {hexval}ff; }}\n"
    )

    # Write-then-rename: a rofi launch during a wallpaper change must never
    # read a half-written file.
    write_atomic(OUTPUT, content)


def hue_neighbours(name):
    """The accent either side of `name` on the perceptual hue wheel.

    The animated border rotates a gradient, so it needs more than one colour to
    show motion. Using the accent's own neighbours keeps the movement visible
    while staying inside one region of the palette.
    """
    order = sorted(ACCENTS, key=lambda n: _hue(ACCENTS[n]))
    i = order.index(name)
    return order[(i - 1) % len(order)], order[(i + 1) % len(order)]


def write_border(name):
    """Write the Hyprland border gradient, atomically.

    Emitted as Lua rather than a .conf snippet: Hyprland's Lua parser refuses
    `hyprctl keyword` ("keyword can't work with non-legacy parsers") and has no
    source directive, so the config reads this file with dofile() instead.
    """
    before, after = hue_neighbours(name)
    stops = ", ".join(f'"rgb({ACCENTS[n].lstrip("#")})"' for n in (before, name, after))

    content = (
        "-- Generated by udt-accent. Do not edit.\n"
        f"return {{ {stops} }}\n"
    )

    write_atomic(BORDER_OUTPUT, content)


def hyprlock_border_content(name):
    """The hyprlock border gradient, as a hyprlang variable assignment.

    The lock panel, its avatar ring and the password outline all take this
    gradient: the same three hues the Hyprland window border rotates through,
    so a wallpaper change recolours the lock with the rest of the desktop.
    One `rgb(hex) rgb(hex) rgb(hex) <angle>` line, which is the syntax the
    input-field already used before it followed the theme.
    """
    before, after = hue_neighbours(name)
    stops = " ".join(f"rgb({ACCENTS[n].lstrip('#')})" for n in (before, name, after))
    return (
        "# Generated by udt-accent. Do not edit.\n"
        f"$border = {stops} 45deg\n"
    )


def write_hyprlock_border(name):
    """Write the hyprlock border gradient, atomically."""
    write_atomic(HYPRLOCK_BORDER_OUTPUT, hyprlock_border_content(name))


def read_palette():
    """Parse palette.rasi into {name: "#rrggbb"}.

    rofi writes colours as #rrggbbaa; QML wants #rrggbb, or #aarrggbb when
    translucent. Only scrim is, so an opaque alpha pair is dropped and any
    other is moved to the front. Returns an empty dict if the file is missing, which leaves the
    QML palette to fall back to its own defaults.
    """
    try:
        text = PALETTE_RASI.read_text()
    except OSError:
        return {}

    found = {}
    for key, value in re.findall(r"(\w+):\s*#([0-9a-fA-F]{6,8})\s*;", text):
        alpha = value[6:].lower()
        found[key] = "#" + (alpha if alpha not in ("", "ff") else "") + value[:6]
    return found


def write_qml(name):
    """Write the palette and current accent as a QML singleton.

    Emitted as QML rather than parsed from palette.rasi by quickshell itself:
    the accent has to reach it anyway, so one generated file carrying both
    means a component needs a single FileView and no rasi parser. It is
    regenerated on every wallpaper change along with the other outputs.
    """
    palette = read_palette()
    if not palette:
        print("udt-accent: palette.rasi unreadable, skipping QML palette",
              file=sys.stderr)
        return

    rows = "\n".join(
        f'    readonly property color {key}: "{value}"'
        for key, value in sorted(palette.items())
    )

    content = (
        "// Generated by udt-accent. Do not edit.\n"
        "//\n"
        f"// The {SCHEME} palette from palette.rasi, plus the accent\n"
        "// currently snapped from the wallpaper. Import it from a quickshell\n"
        "// component and watch this file to follow theme changes.\n"
        "pragma Singleton\n"
        "\n"
        "import QtQuick\n"
        "\n"
        "QtObject {\n"
        f'    readonly property color accent: "{ACCENTS[name]}"\n'
        f'    readonly property string accentName: "{name}"\n'
        "\n"
        f"{rows}\n"
        "}\n"
    )

    write_atomic(QML_OUTPUT, content)


def write_colors_json(name, image):
    """Rewrite colors.json as the scheme's palette with the accent in the highlight slots.

    pywalfox reads this file and nothing else, so this is how Firefox tracks the
    wallpaper. pywal wrote the file moments earlier with wallpaper-derived ANSI
    colours; this replaces them wholesale, which is the point: the terminal
    palette stays the scheme's (udt_colors.PALETTE, which udt-palette
    generates) while only the accent moves.
    """
    hexval = ACCENTS[name]
    colors = list(PALETTE["colors"])
    # Slots 4 and 12 are pywalfox's link/highlight colour.
    colors[4] = colors[12] = hexval

    doc = {
        # Resolved, not as passed: wallp gives the real file but a caller may
        # give ~/.cache/udt/wpaper, the symlink to it. Same wallpaper either
        # way, so record one spelling.
        "wallpaper": os.path.realpath(image),
        "alpha": "100",
        "special": {
            "background": PALETTE["background"],
            "foreground": PALETTE["foreground"],
            "cursor": hexval,
        },
        "colors": {f"color{i}": c for i, c in enumerate(colors)},
    }

    write_atomic(COLORS_JSON, json.dumps(doc, indent=4) + "\n")

    # Firefox only picks the new colours up when pywalfox pushes them. Never
    # fatal: pywalfox may not be installed, and the desktop theme is unaffected.
    subprocess.run(["pywalfox", "update"], capture_output=True, check=False)


def write_firefox(image):
    """Write a blurred wallpaper into FF Ultima's darknix.png new tab slot.

    Blurred so the new tab reads as Firefox, not as a hole onto the desktop.
    A file, not a link: Firefox's sandbox refuses to follow a symlink out of
    the profile, and the new tab shows nothing. Every profile without FF
    Ultima is skipped.

    A failure is reported, not raised: the new tab is cosmetic, and main()
    still has GRUB, the homepage and the helpers to do after it.
    """
    from PIL import Image, ImageFilter

    try:
        blurred = None
        for walls in (Path.home() / ".mozilla" / "firefox").glob(f"*/{FIREFOX_WALLS}"):
            if blurred is None:
                with Image.open(image) as im:
                    im = im.convert("RGB")
                    # Detail is blurred away anyway, so 1920 wide is plenty
                    # and keeps the blur fast on a 4K wallpaper.
                    im.thumbnail((1920, 1920))
                    blurred = im.filter(ImageFilter.GaussianBlur(FIREFOX_BLUR))
            dest = walls / "darknix.png"
            # A leftover link would make save write through it into the
            # wallpaper itself.
            dest.unlink(missing_ok=True)
            blurred.save(dest, "PNG")
    except Exception as exc:
        print(f"udt-accent: firefox new tab not updated: {exc}", file=sys.stderr)


def rewrite(path, pattern, value):
    """Replace group 1's tail in the first line matching pattern with value.

    For generated files whose accent is replaced by matching the line that
    carries it, not a placeholder, so a second run rewrites the first run's
    accent. A missing file is not an error: its consumer may not be here.
    """
    try:
        text = path.read_text()
    except FileNotFoundError:
        return
    new, count = re.subn(pattern, lambda m: m.group(1) + value, text,
                         count=1, flags=re.M)
    if count and new != text:
        write_atomic(path, new, mode=path.stat().st_mode & 0o777)


def write_sublime(name):
    """Substitute the accent into the Sublime colour scheme install.sh copied.

    In place: Sublime colour schemes do not cascade, so the accent cannot
    arrive as a second file. Sublime watches Packages/User and reloads a
    scheme when its file changes, so no signal is needed.
    """
    rewrite(SUBLIME, r'("accent":\s*")[^"]*', ACCENTS[name])


def write_grub(name):
    """The accent on theme.txt's '# udt:' line, which GRUB's build reads."""
    rewrite(GRUB_THEME, r"^(# udt: .*\baccent=)#[0-9a-fA-F]{6}", ACCENTS[name])


def write_homepage(name):
    """The --udt-accent triple every accent in homepage's custom.css reads."""
    r, g, b = bytes.fromhex(ACCENTS[name].lstrip("#"))
    rewrite(HOMEPAGE_CSS, r"^(\s*--udt-accent:\s*)[^;]*", f"{r} {g} {b}")


def icon_theme():
    """The icon theme the appearance drawer selected, or "" if unreadable.

    gsettings runs as the login user, so it reads the user's dconf. Empty on
    any failure: the theme then keeps its bundled power icons.
    """
    try:
        got = subprocess.run(["gsettings", "get", ICON_SCHEMA, ICON_KEY],
                             capture_output=True, text=True, check=True)
    except (OSError, subprocess.CalledProcessError):
        return ""
    return got.stdout.strip().strip("'")


def find_icon(theme, names, dirs=None):
    """Absolute path to the first of `names` present in `theme`, else "".

    The names are tried in order: the first that has any match wins. For that
    name a theme may ship the icon flat or as a symbolic variant at several
    sizes. Prefer the symbolic variant, then the largest size directory, where
    `16x16`, `24x24`, `48x48`, a plain `16`/`48` and `scalable` are all parsed
    and `scalable` counts as larger than any pixel size. `dirs` is injectable
    for the selftest.
    """
    if not theme:
        return ""
    dirs = ICON_DIRS if dirs is None else dirs

    def rank(path):
        symbolic = path.stem.endswith("-symbolic")
        scalable = False
        size = 0
        for part in path.parts:
            if part == "scalable":
                scalable = True
                continue
            match = re.fullmatch(r"(\d+)(?:x\d+)?", part)
            if match:
                size = max(size, int(match.group(1)))
        return (symbolic, scalable, size)

    for name in names:
        stems = {name, f"{name}-symbolic"}
        for base in dirs:
            root = base / theme
            if not root.is_dir():
                continue
            matches = [p for p in root.rglob("*.svg") if p.stem in stems]
            if matches:
                return str(max(matches, key=rank))
    return ""


def power_icons():
    """The four power icon paths, resolved from the selected icon theme."""
    theme = icon_theme()
    return {key: find_icon(theme, names) for key, names in POWER_ICONS.items()}


def screen_wallpapers(conf=WALLP):
    """Each output's wallpaper, {output: path}, from wallp's conf and state.

    Empty when wallp is not set up; a screen with no saved wallpaper is left
    out. Either way the greeter falls back to `background` for that screen.
    """
    outputs = {}
    try:
        for line in (conf / "wallp.conf").read_text().splitlines():
            key, _, val = line.partition("=")
            if key in ("OUTPUT_H", "OUTPUT_V") and val:
                outputs[key[-1]] = val
    except OSError:
        return {}
    walls = {}
    for side, output in outputs.items():
        try:
            path = (conf / f"wall_{side.lower()}").read_text().strip()
        except OSError:
            continue
        if path:
            walls[output] = os.path.realpath(path)
    return walls


def sddm_conf(palette, name, image, icons=None, avatar="", walls=None):
    """The SDDM theme config, as an INI fragment.

    theme.conf.user overrides theme.conf and is exposed to the theme as the
    `config` object. It is data parsed by QSettings, never executed, so nothing
    the login user can write reaches the greeter as code.
    """
    lines = [
        "# Generated by udt-accent. Do not edit.",
        "[General]",
        "type=image",
        f"background={os.path.realpath(image)}",
        f"accent={ACCENTS[name]}",
    ]
    # Per-screen wallpapers, keyed by output name. The greeter prefers these
    # over `background` on the screen they name.
    lines += [f"background_{out}={path}" for out, path in (walls or {}).items()]
    lines += [f"{key}={palette.get(key, '#000000')}" for key in SDDM_KEYS]
    icons = icons or {}
    lines += [f"{key}={icons.get(key, '')}" for key in POWER_ICONS]
    # The avatar belongs to whoever ran udt-accent; the greeter only uses it
    # when that username is the one being logged in.
    lines += [f"avatarUser={getpass.getuser() if avatar else ''}",
              f"avatar={avatar}"]
    return "\n".join(lines) + "\n"


def write_sddm(name, image):
    """Write the live SDDM palette, atomically, world-readable.

    World-readable because the greeter runs as the sddm user, and traversable
    for the same reason. Both modes are set before the rename, so the greeter
    never sees an unreadable file or directory.
    """
    palette = read_palette()
    if not palette:
        print("udt-accent: palette.rasi unreadable, skipping SDDM theme",
              file=sys.stderr)
        return
    write_atomic(SDDM_OUTPUT, sddm_conf(palette, name, image, power_icons(),
                           str(AVATAR) if AVATAR.is_file() else "",
                           screen_wallpapers()),
                 mode=0o644, dir_mode=0o755)


def main(image):
    try:
        color = signature_color(image)
        name = snap(color) if color else FALLBACK
    except Exception as exc:
        # A broken image must still leave a working theme.
        print(f"udt-accent: {exc}, falling back to {FALLBACK}", file=sys.stderr)
        name = FALLBACK

    write_accent(name)
    write_border(name)
    write_hyprlock_border(name)
    write_qml(name)
    write_sublime(name)
    write_sddm(name, image)
    write_colors_json(name, image)
    write_firefox(image)
    # Before the helpers below start, which build and stage these two.
    write_grub(name)
    write_homepage(name)

    # Hyprland only rereads its config on request, and may not be running.
    subprocess.run(["hyprctl", "reload"], capture_output=True, check=False)

    # The dashboard host. Detached, because wallp runs this synchronously and
    # an unreachable host would hold the wallpaper change for the scp timeout.
    # GRUB's background is a wallpaper snapshot. Detached for the same reason;
    # it only rebuilds and notifies, since the copy into /boot needs root.
    # The keyboard takes seconds per colour change, and is often not there.
    # The LED strip waits up to 20 s for its address broadcast, the bulbs
    # up to 5 s per bulb for the gateway. All three read files written above.
    for helper in ("udt-homepage", "udt-grub", "udt-keyboard", "udt-ledstrip", "udt-bulb"):
        subprocess.Popen([Path(__file__).resolve().parent / helper],
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
                         stderr=subprocess.DEVNULL, start_new_session=True)

    before, after = hue_neighbours(name)
    print(f"{name} {ACCENTS[name]} (border: {before} .. {name} .. {after})")


def selftest():
    # Every accent must snap to itself, or the metric is not self-consistent.
    for name, hexval in ACCENTS.items():
        got = snap(hexval)
        assert got == name, f"{name} ({hexval}) snapped to {got}"

    # Representative real-world inputs. Asserted by hue rather than by name:
    # the accent table is generated, so the colour an orange input snaps to is
    # called "peach" under Catppuccin and "orange" under Tokyo Night.
    for probe in ("#ff8800", "#00cc44", "#3366ff"):
        got = snap(probe)
        delta = abs(_hue(ACCENTS[got]) - _hue(probe))
        delta = min(delta, 2 * math.pi - delta)
        assert delta < 0.6, f"{probe} snapped to {got}, {delta:.2f} rad away"

    # The Sublime accent is replaced by matching its current value, not a
    # placeholder, so it has to survive being run twice: once over the freshly
    # installed @ACCENT@, and again over the accent it wrote last time.
    probe = '{\n    "variables":\n    {\n        "accent":   "@ACCENT@",\n'
    first, n1 = re.subn(r'("accent":\s*)"[^"]*"', r'\1"#f5a97f"', probe, count=1)
    second, n2 = re.subn(r'("accent":\s*)"[^"]*"', r'\1"#8bd5ca"', first, count=1)
    third, n3 = re.subn(r'("accent":\s*)"[^"]*"', r'\1"#8bd5ca"', second, count=1)
    assert (n1, n2, n3) == (1, 1, 1), (n1, n2, n3)
    assert "@ACCENT@" not in first and '"#f5a97f"' in first
    assert '"#f5a97f"' not in second and '"#8bd5ca"' in second
    assert third == second, "accent substitution is not idempotent"

    # GRUB and homepage go through the same match-the-line rewrite, so the
    # same twice-over test: the scheme's accent first, then the last run's.
    with tempfile.TemporaryDirectory() as tmpdir:
        f = Path(tmpdir) / "f"
        cases = [
            (write_grub, "# udt: bg_alt=#1e2030 accent=#b7bdf8\nx = \"#b7bdf8\"\n",
             lambda h: f"# udt: bg_alt=#1e2030 accent={h}\nx = \"#b7bdf8\"\n"),
            (write_homepage, ".t {\n  --udt-accent: 183 189 248;\n}\n",
             lambda h: ".t {\n  --udt-accent: %d %d %d;\n}\n"
             % tuple(bytes.fromhex(h[1:]))),
        ]
        for write, start, want in cases:
            globals()["GRUB_THEME"] = globals()["HOMEPAGE_CSS"] = f
            f.write_text(start)
            f.chmod(0o644)
            for name in list(ACCENTS)[:2]:
                write(name)
                assert f.read_text() == want(ACCENTS[name]), f.read_text()
            assert f.stat().st_mode & 0o777 == 0o644, "rewrite lost the mode"

    # A near-grey has an unstable hue angle and must take the fallback.
    assert snap("#888888") == FALLBACK, snap("#888888")

    # The accent is what stands out, not what covers the most: a small violet
    # patch on a frame of pale skin tone must win, and a grey image has none.
    import io
    from PIL import Image

    def png(size, fill, patch=None):
        im = Image.new("RGB", size, fill)
        if patch:
            im.paste(patch, (10, 10, 30, 30))
        buf = io.BytesIO()
        im.save(buf, "PNG")
        buf.seek(0)
        return buf

    got = signature_color(png((200, 100), "#e8b8a8", "#6a39b0"))
    delta = abs(_hue(got) - _hue("#6a39b0"))
    assert min(delta, 2 * math.pi - delta) < 0.2, got
    assert signature_color(png((200, 100), "#777777", "#7a7a80")) is None
    assert FALLBACK in ACCENTS, FALLBACK

    # Border neighbours must be distinct from the accent and from each other,
    # or the gradient has nothing to animate between.
    for name in ACCENTS:
        before, after = hue_neighbours(name)
        assert len({before, name, after}) == 3, (name, before, after)
    # Neighbours are the adjacent hues on the wheel, so each sits nearer to
    # the accent than the accent's opposite does.
    for name in ACCENTS:
        before, after = hue_neighbours(name)
        for neighbour in (before, after):
            delta = abs(_hue(ACCENTS[neighbour]) - _hue(ACCENTS[name]))
            assert min(delta, 2 * math.pi - delta) < math.pi, (name, neighbour)

    # The lock border carries the same three hues as the window border, in
    # hyprlang gradient syntax: three rgb() stops and an angle. Get it wrong and
    # the panel border, avatar ring and password outline all draw hyprlock's
    # default cyan instead of the accent.
    lock = hyprlock_border_content(FALLBACK)
    assert lock.count("rgb(") == 3, lock
    assert lock.rstrip().endswith("45deg"), lock
    assert "$border = " in lock, lock

    # The SDDM theme reads this file through a symlink, so it has to carry every
    # key the theme asks for. The names are spelled out here rather than read
    # from SDDM_KEYS: deriving both the input and the check from the same
    # constant would still pass if a key were dropped from the writer's list.
    expected_keys = [
        "base", "mantle", "crust", "surface0", "surface1", "surface2",
        "text", "subtext0", "subtext1", "overlay0", "overlay1", "overlay2",
        "red", "yellow", "green", "teal", "blue", "lavender",
    ]
    with tempfile.TemporaryDirectory() as tmpdir:
        probe_image = Path(tmpdir) / "wall.png"
        probe_image.write_bytes(b"")
        palette = {k: "#1e2030" for k in expected_keys}
        text = sddm_conf(palette, FALLBACK, str(probe_image))
        for key in ["type", "background", "accent", *expected_keys]:
            assert f"\n{key}=" in "\n" + text, f"sddm conf missing {key}"
        assert text.count("accent=") == 1
        assert "background=" + os.path.realpath(probe_image) in text

        # A second run has to overwrite cleanly rather than append: the greeter
        # rereads this file through a symlink on every login.
        target = Path(tmpdir) / "sddm-theme.conf"
        write_atomic(target, text)
        write_atomic(target, sddm_conf(palette, FALLBACK, str(probe_image)))
        assert target.read_text() == text, "second write changed the output"
        assert target.read_text().count("[General]") == 1, "second write appended"

        # The greeter runs as another user, so file and directory modes must be
        # set on the temp file before the rename. Fixing the mode up after the
        # rename leaves a moment where the greeter can read a 0600 file.
        readable = Path(tmpdir) / "readable.conf"
        write_atomic(readable, text, mode=0o644)
        assert readable.stat().st_mode & 0o777 == 0o644, \
            oct(readable.stat().st_mode & 0o777)

        outdir = Path(tmpdir) / "sub" / "udt"
        writable = outdir / "f.conf"
        write_atomic(writable, text, mode=0o644, dir_mode=0o755)
        assert outdir.stat().st_mode & 0o777 == 0o755, \
            oct(outdir.stat().st_mode & 0o777)

    # Power icons: an unknown or empty theme resolves to empty, so the greeter
    # falls back to its bundled SVGs; a real theme prefers the symbolic variant
    # at the largest size, and a name list is tried in order.
    assert find_icon("", ["system-shutdown"]) == ""
    assert find_icon("no-such-theme-udt", ["system-shutdown"]) == ""
    with tempfile.TemporaryDirectory() as tmpdir:
        root = Path(tmpdir) / "icons"
        base = root / "probe"
        (base / "actions" / "16").mkdir(parents=True)
        (base / "actions" / "symbolic").mkdir(parents=True)
        (base / "actions" / "16" / "system-shutdown.svg").write_text("<svg/>")
        (base / "actions" / "symbolic" / "system-shutdown-symbolic.svg").write_text("<svg/>")
        got = find_icon("probe", ["system-shutdown"], dirs=[root])
        assert got.endswith("actions/symbolic/system-shutdown-symbolic.svg"), got
        (base / "actions" / "symbolic" / "system-shutdown-symbolic.svg").unlink()
        got = find_icon("probe", ["system-shutdown"], dirs=[root])
        assert got.endswith("actions/16/system-shutdown.svg"), got
        assert find_icon("probe", ["system-hibernate", "system-suspend-hibernate"],
                         dirs=[root]) == ""

    # Among the sizes one name ships at, the largest directory wins. Both the
    # WxH and plain-number spellings parse, and scalable is treated as largest.
    with tempfile.TemporaryDirectory() as tmpdir:
        root = Path(tmpdir) / "icons"
        actions = root / "probe" / "actions"
        for sub in ("16x16", "48x48"):
            (actions / sub).mkdir(parents=True)
            (actions / sub / "system-shutdown.svg").write_text("<svg/>")
        got = find_icon("probe", ["system-shutdown"], dirs=[root])
        assert got.endswith("actions/48x48/system-shutdown.svg"), got
        (actions / "scalable").mkdir()
        (actions / "scalable" / "system-shutdown.svg").write_text("<svg/>")
        got = find_icon("probe", ["system-shutdown"], dirs=[root])
        assert got.endswith("actions/scalable/system-shutdown.svg"), got

    # The first name in the list that exists wins, even when a later name also
    # has a match.
    with tempfile.TemporaryDirectory() as tmpdir:
        root = Path(tmpdir) / "icons"
        base = root / "probe" / "actions" / "48"
        base.mkdir(parents=True)
        (base / "system-shutdown.svg").write_text("<svg/>")
        (base / "system-reboot.svg").write_text("<svg/>")
        got = find_icon("probe", ["system-shutdown", "system-reboot"], dirs=[root])
        assert got.endswith("actions/48/system-shutdown.svg"), got
        got = find_icon("probe", ["system-reboot", "system-shutdown"], dirs=[root])
        assert got.endswith("actions/48/system-reboot.svg"), got

    with tempfile.TemporaryDirectory() as tmpdir:
        probe_image = Path(tmpdir) / "wall.png"
        probe_image.write_bytes(b"")
        palette = {k: "#1e2030" for k in SDDM_KEYS}
        icons = {"powerIcon": "/tmp/power.svg", "rebootIcon": "",
                 "suspendIcon": "", "hibernateIcon": ""}
        text = sddm_conf(palette, FALLBACK, str(probe_image), icons)
        for key in ("powerIcon", "rebootIcon", "suspendIcon", "hibernateIcon"):
            assert f"\n{key}=" in "\n" + text, f"sddm conf missing {key}"
        assert "\npowerIcon=/tmp/power.svg" in "\n" + text

        # No avatar leaves both keys empty so the greeter falls back to
        # AccountsService; a set one names the user it belongs to.
        assert "\navatar=\n" in "\n" + text and "\navatarUser=\n" in "\n" + text
        text = sddm_conf(palette, FALLBACK, str(probe_image), icons, "/tmp/me.jpg")
        assert "\navatar=/tmp/me.jpg\n" in "\n" + text
        assert f"\navatarUser={getpass.getuser()}\n" in "\n" + text

    # Per-screen wallpapers come from wallp's output names and saved state; a
    # screen with no saved wallpaper is left out, and no wallp at all gives none.
    with tempfile.TemporaryDirectory() as tmpdir:
        conf = Path(tmpdir)
        assert screen_wallpapers(conf) == {}
        (conf / "wallp.conf").write_text("# c\nOUTPUT_H=DP-1\nOUTPUT_V=DP-3\nDEFAULT_H=~/x\n")
        (conf / "wall_h").write_text("/tmp/h.jpg\n")
        assert screen_wallpapers(conf) == {"DP-1": "/tmp/h.jpg"}
        (conf / "wall_v").write_text("/tmp/v.png\n")
        walls = screen_wallpapers(conf)
        assert walls == {"DP-1": "/tmp/h.jpg", "DP-3": "/tmp/v.png"}, walls
        text = sddm_conf({}, FALLBACK, "/tmp/h.jpg", walls=walls)
        assert "\nbackground_DP-1=/tmp/h.jpg\n" in text
        assert "\nbackground_DP-3=/tmp/v.png\n" in text

    got = power_icons()
    assert set(got) == {"powerIcon", "rebootIcon", "suspendIcon", "hibernateIcon"}

    # write_firefox: a real image lands blurred and capped at 1920, and a
    # broken one is reported rather than raised, so main() carries on.
    from PIL import Image
    with tempfile.TemporaryDirectory() as tmp:
        home = os.environ.get("HOME")
        os.environ["HOME"] = tmp
        try:
            walls = Path(tmp) / ".mozilla" / "firefox" / "p.default" / FIREFOX_WALLS
            walls.mkdir(parents=True)
            src = Path(tmp) / "wall.png"
            Image.new("RGB", (3840, 2160), "#336699").save(src)
            write_firefox(src)
            with Image.open(walls / "darknix.png") as out:
                assert out.size == (1920, 1080) and out.mode == "RGB", out
            bad = Path(tmp) / "bad.jpg"
            bad.write_text("not an image")
            write_firefox(bad)
        finally:
            os.environ["HOME"] = home

    print("selftest OK")


if __name__ == "__main__":
    args = sys.argv[1:]
    if args == ["--selftest"]:
        selftest()
    elif args in (["-h"], ["--help"]):
        print(__doc__)
    elif len(args) == 1 and not args[0].startswith("-") and os.path.isfile(args[0]):
        main(args[0])
    else:
        # An unknown option or a missing file would otherwise be taken as the
        # wallpaper, and its path written into SDDM's config and colors.json.
        print(__doc__, file=sys.stderr)
        sys.exit(2)