euv 0.49.4

A high-performance cross-platform native UI framework for Rust targeting Web, Android, iOS, iPadOS, macOS, Windows, and Linux with direct system APIs, fine-grained reactivity, and multi-mode rendering.
Documentation
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
#!/usr/bin/env python3
"""Generate cross-platform Euv app icons from the canonical remote logo URL.

Supports PNG, Windows ICO, macOS ICNS, and complete multi-platform icon suites
with zero external Python dependencies (optional Pillow/sips acceleration).

Usage:
    generate-icon.py <output_png_or_ico_or_icns> <size_px> [custom_source_png_or_url]
    generate-icon.py --all [--output-dir <dir>] [--source <png>] [--url <url>]
    generate-icon.py --icns <output_icns> [--source <png>] [--url <url>]
    generate-icon.py --ico <output_ico> [--source <png>] [--url <url>]
"""

from __future__ import annotations

import argparse
import gzip
import hashlib
import json
import os
import shutil
import struct
import subprocess
import sys
import tempfile
import urllib.request
import zlib
from pathlib import Path
from typing import Iterable, Optional, Sequence

# Canonical brand logo URL shared across READMEs, docs, web bundles, and icon downloads.
DEFAULT_LOGO_URL: str = "https://devhub.vip/pages/docs/img/euv.png"

# Standard square RGBA transparent PNG export dimensions.
BRANDING_SIZES: tuple[int, ...] = (1024, 512, 256, 192, 180, 128, 64, 32)

# Windows ICO embedded PNG frame dimensions.
ICO_SIZES: tuple[int, ...] = (16, 32, 48, 64, 128, 256)

# macOS ICNS modern PNG chunk tags paired with square pixel dimensions.
ICNS_SPECS: tuple[tuple[bytes, int], ...] = (
    (b"icp4", 16),
    (b"icp5", 32),
    (b"icp6", 64),
    (b"ic07", 128),
    (b"ic08", 256),
    (b"ic09", 512),
    (b"ic10", 1024),
)

# Android & Wear OS mipmap launcher icon densities.
ANDROID_MIPMAP_SPECS: tuple[tuple[str, int], ...] = (
    ("mipmap-mdpi", 48),
    ("mipmap-hdpi", 72),
    ("mipmap-xhdpi", 96),
    ("mipmap-xxhdpi", 144),
    ("mipmap-xxxhdpi", 192),
)

# iOS & iPadOS AppIcon.appiconset image descriptors.
IOS_ICON_SPECS: tuple[tuple[str, int, str, str, str], ...] = (
    ("AppIcon-60@2x.png", 120, "60x60", "iphone", "2x"),
    ("AppIcon-60@3x.png", 180, "60x60", "iphone", "3x"),
    ("AppIcon-76@2x.png", 152, "76x76", "ipad", "2x"),
    ("AppIcon-83.5@2x.png", 167, "83.5x83.5", "ipad", "2x"),
    ("AppIcon-1024.png", 1024, "1024x1024", "ios-marketing", "1x"),
)

# Apple watchOS AppIcon.appiconset image descriptors.
WATCHOS_ICON_SPECS: tuple[tuple[str, int, str, str], ...] = (
    ("AppIcon-88.png", 88, "44x44", "2x"),
    ("AppIcon-100.png", 100, "50x50", "2x"),
    ("AppIcon-1024.png", 1024, "1024x1024", "1x"),
)


def _repo_root() -> Path:
    return Path(__file__).resolve().parents[2]




def _is_valid_png_file(path: Path) -> bool:
    try:
        with path.open("rb") as f:
            return f.read(8) == b"\x89PNG\r\n\x1a\n"
    except OSError:
        return False


def _icon_cache_dir() -> Path:
    repo_target = _repo_root() / "target" / "euv-icon-cache"
    try:
        repo_target.mkdir(parents=True, exist_ok=True)
        return repo_target
    except OSError:
        fallback = Path(tempfile.gettempdir()) / "euv-icon-cache"
        fallback.mkdir(parents=True, exist_ok=True)
        return fallback


def _download_remote_logo(url: str) -> Optional[Path]:
    """Download and cache the canonical PNG logo from `url`, returning the cached path or None."""
    digest = hashlib.sha256(url.encode("utf-8")).hexdigest()[:16]
    cache_path = _icon_cache_dir() / f"euv-logo-{digest}.png"
    if _is_valid_png_file(cache_path):
        return cache_path

    tmp_path = cache_path.with_suffix(".tmp")
    try:
        req = urllib.request.Request(
            url,
            headers={
                "User-Agent": "euv-icon-fetcher/1.0",
                "Accept-Encoding": "gzip, deflate",
            },
        )
        with urllib.request.urlopen(req, timeout=20) as resp:
            data = resp.read()
            encoding = (resp.headers.get("Content-Encoding") or "").lower()
            if "gzip" in encoding or data[:2] == b"\x1f\x8b":
                data = gzip.decompress(data)
            elif "deflate" in encoding:
                data = zlib.decompress(data)
        if data[:8] == b"\x89PNG\r\n\x1a\n":
            tmp_path.write_bytes(data)
            os.replace(tmp_path, cache_path)
            return cache_path
    except Exception:
        pass
    finally:
        if tmp_path.exists():
            try:
                tmp_path.unlink()
            except OSError:
                pass

    if shutil.which("curl"):
        try:
            subprocess.run(
                ["curl", "-fsSL", "--compressed", "--max-time", "20", url, "-o", str(tmp_path)],
                check=True,
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL,
            )
            if _is_valid_png_file(tmp_path):
                os.replace(tmp_path, cache_path)
                return cache_path
        except Exception:
            if tmp_path.exists():
                try:
                    tmp_path.unlink()
                except OSError:
                    pass
    return None


def resolve_source_png(
    explicit_source: Optional[str] = None,
    explicit_url: Optional[str] = None,
) -> Path:
    """Resolve the canonical RGBA PNG logo by downloading from the remote URL (or explicit override)."""
    if explicit_source:
        src_path = Path(explicit_source)
        if src_path.is_file() and _is_valid_png_file(src_path):
            return src_path
        if explicit_source.startswith(("http://", "https://")):
            downloaded = _download_remote_logo(explicit_source)
            if downloaded is not None:
                return downloaded

    env_icon = os.environ.get("EUV_APP_ICON", "").strip()
    if env_icon:
        env_path = Path(env_icon)
        if env_path.is_file() and _is_valid_png_file(env_path):
            return env_path
        if env_icon.startswith(("http://", "https://")):
            downloaded = _download_remote_logo(env_icon)
            if downloaded is not None:
                return downloaded

    remote_url = explicit_url or os.environ.get("EUV_APP_ICON_URL", DEFAULT_LOGO_URL)
    if remote_url:
        downloaded = _download_remote_logo(remote_url)
        if downloaded is not None:
            return downloaded

    raise RuntimeError(
        f"Unable to download canonical Euv logo from {remote_url}"
    )


def _encode_png_bytes(width: int, height: int, rgba: bytes) -> bytes:
    """Encode an 8-bit RGBA PNG byte buffer deterministically using only Python stdlib."""

    def chunk(tag: bytes, data: bytes) -> bytes:
        return (
            struct.pack(">I", len(data))
            + tag
            + data
            + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
        )

    raw = bytearray()
    stride = width * 4
    for y in range(height):
        raw.append(0)
        raw.extend(rgba[y * stride : (y + 1) * stride])
    ihdr = struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0)
    return (
        b"\x89PNG\r\n\x1a\n"
        + chunk(b"IHDR", ihdr)
        + chunk(b"IDAT", zlib.compress(bytes(raw), 9))
        + chunk(b"IEND", b"")
    )


def write_png(path: str, width: int, height: int, rgba: bytes) -> None:
    """Write an 8-bit RGBA PNG file deterministically with zero external dependencies."""
    parent = os.path.dirname(os.path.abspath(path))
    if parent:
        os.makedirs(parent, exist_ok=True)
    with open(path, "wb") as f:
        f.write(_encode_png_bytes(width, height, rgba))


def _decode_png_rgba_stdlib(path: Path) -> tuple[int, int, bytes]:
    """Decode an 8-bit non-interlaced PNG (RGBA/RGB/Indexed/Grayscale) using stdlib only."""
    data = path.read_bytes()
    if data[:8] != b"\x89PNG\r\n\x1a\n":
        raise ValueError(f"Not a PNG file: {path}")
    pos = 8
    width = height = bit_depth = color_type = interlace = 0
    plte = b""
    trns = b""
    idat = bytearray()
    while pos < len(data):
        length = struct.unpack(">I", data[pos : pos + 4])[0]
        ctype = data[pos + 4 : pos + 8]
        cdata = data[pos + 8 : pos + 8 + length]
        pos += 12 + length
        if ctype == b"IHDR":
            width, height, bit_depth, color_type, _, _, interlace = struct.unpack(">IIBBBBB", cdata)
        elif ctype == b"PLTE":
            plte = cdata
        elif ctype == b"tRNS":
            trns = cdata
        elif ctype == b"IDAT":
            idat.extend(cdata)
        elif ctype == b"IEND":
            break
    if bit_depth != 8 or interlace != 0:
        raise ValueError(f"Unsupported PNG format (bit_depth={bit_depth}, interlace={interlace})")
    bpp_map = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}
    if color_type not in bpp_map:
        raise ValueError(f"Unsupported PNG color_type={color_type}")
    bpp = bpp_map[color_type]
    raw = zlib.decompress(bytes(idat))
    stride = width * bpp
    recon = bytearray(height * stride)
    for y in range(height):
        row_in_base = y * (stride + 1)
        ftype = raw[row_in_base]
        row_out = y * stride
        prev_out = (y - 1) * stride
        for x in range(stride):
            a = recon[row_out + x - bpp] if x >= bpp else 0
            b = recon[prev_out + x] if y > 0 else 0
            c = recon[prev_out + x - bpp] if (y > 0 and x >= bpp) else 0
            v = raw[row_in_base + 1 + x]
            if ftype == 0:
                p = v
            elif ftype == 1:
                p = (v + a) & 0xFF
            elif ftype == 2:
                p = (v + b) & 0xFF
            elif ftype == 3:
                p = (v + ((a + b) >> 1)) & 0xFF
            elif ftype == 4:
                pa = abs(b - c)
                pb = abs(a - c)
                pc = abs(a + b - 2 * c)
                pr = a if (pa <= pb and pa <= pc) else (b if pb <= pc else c)
                p = (v + pr) & 0xFF
            else:
                raise ValueError(f"Invalid PNG filter type {ftype}")
            recon[row_out + x] = p

    if color_type == 6:
        return width, height, bytes(recon)

    rgba = bytearray(width * height * 4)
    if color_type == 3:
        for i, idx in enumerate(recon):
            p = i * 4
            rgba[p] = plte[idx * 3]
            rgba[p + 1] = plte[idx * 3 + 1]
            rgba[p + 2] = plte[idx * 3 + 2]
            rgba[p + 3] = trns[idx] if idx < len(trns) else 255
    elif color_type == 2:
        for i in range(width * height):
            p = i * 4
            s = i * 3
            rgba[p] = recon[s]
            rgba[p + 1] = recon[s + 1]
            rgba[p + 2] = recon[s + 2]
            rgba[p + 3] = 255
    elif color_type == 4:
        for i in range(width * height):
            p = i * 4
            s = i * 2
            g = recon[s]
            rgba[p] = g
            rgba[p + 1] = g
            rgba[p + 2] = g
            rgba[p + 3] = recon[s + 1]
    elif color_type == 0:
        for i, g in enumerate(recon):
            p = i * 4
            rgba[p] = g
            rgba[p + 1] = g
            rgba[p + 2] = g
            rgba[p + 3] = 255
    return width, height, bytes(rgba)


def _resample_rgba_premult_stdlib(w: int, h: int, rgba: bytes, dst_size: int) -> bytes:
    """Premultiplied-alpha box/bilinear resampler in pure Python (zero dependencies)."""
    if w == dst_size and h == dst_size:
        return rgba
    out = bytearray(dst_size * dst_size * 4)
    scale_x = w / float(dst_size)
    scale_y = h / float(dst_size)
    if dst_size <= w and dst_size <= h:
        for dy in range(dst_size):
            y0 = int(dy * scale_y)
            y1 = max(y0 + 1, min(h, int((dy + 1) * scale_y)))
            for dx in range(dst_size):
                x0 = int(dx * scale_x)
                x1 = max(x0 + 1, min(w, int((dx + 1) * scale_x)))
                sr = sg = sb = sa = 0.0
                cnt = 0
                for sy in range(y0, y1):
                    row = sy * w * 4
                    for sx in range(x0, x1):
                        p = row + sx * 4
                        a = rgba[p + 3] / 255.0
                        sr += rgba[p] * a
                        sg += rgba[p + 1] * a
                        sb += rgba[p + 2] * a
                        sa += a
                        cnt += 1
                di = (dy * dst_size + dx) * 4
                if sa > 1e-6:
                    out[di] = min(255, int(round(sr / sa)))
                    out[di + 1] = min(255, int(round(sg / sa)))
                    out[di + 2] = min(255, int(round(sb / sa)))
                    out[di + 3] = min(255, int(round((sa / cnt) * 255.0)))
    else:
        for dy in range(dst_size):
            fy = (dy + 0.5) * scale_y - 0.5
            y0 = max(0, min(h - 1, int(fy)))
            y1 = min(h - 1, y0 + 1)
            wy = max(0.0, min(1.0, fy - y0))
            for dx in range(dst_size):
                fx = (dx + 0.5) * scale_x - 0.5
                x0 = max(0, min(w - 1, int(fx)))
                x1 = min(w - 1, x0 + 1)
                wx = max(0.0, min(1.0, fx - x0))
                p00 = (y0 * w + x0) * 4
                p10 = (y0 * w + x1) * 4
                p01 = (y1 * w + x0) * 4
                p11 = (y1 * w + x1) * 4
                weights = (
                    (p00, (1.0 - wx) * (1.0 - wy)),
                    (p10, wx * (1.0 - wy)),
                    (p01, (1.0 - wx) * wy),
                    (p11, wx * wy),
                )
                sr = sg = sb = sa = 0.0
                for p, wt in weights:
                    a = (rgba[p + 3] / 255.0) * wt
                    sr += rgba[p] * a
                    sg += rgba[p + 1] * a
                    sb += rgba[p + 2] * a
                    sa += a
                di = (dy * dst_size + dx) * 4
                if sa > 1e-6:
                    out[di] = min(255, int(round(sr / sa)))
                    out[di + 1] = min(255, int(round(sg / sa)))
                    out[di + 2] = min(255, int(round(sb / sa)))
                    out[di + 3] = min(255, int(round(sa * 255.0)))
    return bytes(out)


def _premult_lanczos_pil(rgba_img: object, size: int) -> object:
    from PIL import Image

    try:
        import numpy as np

        arr = np.asarray(rgba_img, dtype=np.float32) / 255.0
        pm = np.empty_like(arr)
        pm[..., :3] = arr[..., :3] * arr[..., 3:4]
        pm[..., 3:4] = arr[..., 3:4]
        pm_img = Image.fromarray(np.clip(np.round(pm * 255.0), 0, 255).astype(np.uint8))
        pm_res = pm_img.resize((size, size), Image.Resampling.LANCZOS)
        pr = np.asarray(pm_res, dtype=np.float32) / 255.0
        out = np.zeros_like(pr)
        a = pr[..., 3:4]
        out[..., :3] = np.where(a > 1e-4, np.clip(pr[..., :3] / np.maximum(a, 1e-4), 0.0, 1.0), 0.0)
        out[..., 3:4] = np.where(a > 1.0 / 255.0, a, 0.0)
        return Image.fromarray(np.clip(np.round(out * 255.0), 0, 255).astype(np.uint8))
    except ImportError:
        return rgba_img.resize((size, size), Image.Resampling.LANCZOS)


class _SourceRasterCache:
    """Caches decoded source RGBA pixels and rendered PNG bytes per size during multi-icon exports."""

    def __init__(self, source_png: Path) -> None:
        self.source_png = source_png
        self._decoded: Optional[tuple[int, int, bytes]] = None
        self._png_cache: dict[int, bytes] = {}

    def png_bytes_for_size(self, size: int) -> bytes:
        cached = self._png_cache.get(size)
        if cached is not None:
            return cached

        # Fast path 1: Pillow premultiplied-Lanczos.
        try:
            from io import BytesIO
            from PIL import Image

            with Image.open(self.source_png) as img:
                rgba = img.convert("RGBA")
                resized = _premult_lanczos_pil(rgba, size)
                buf = BytesIO()
                resized.save(buf, format="PNG", optimize=True)
                data = buf.getvalue()
                self._png_cache[size] = data
                return data
        except ImportError:
            pass

        # Fast path 2: macOS sips native CoreGraphics resampler.
        if shutil.which("sips"):
            with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tf:
                tmp_out = tf.name
            try:
                subprocess.run(
                    [
                        "sips",
                        "-z",
                        str(size),
                        str(size),
                        "-s",
                        "format",
                        "png",
                        str(self.source_png),
                        "--out",
                        tmp_out,
                    ],
                    check=True,
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL,
                )
                data = Path(tmp_out).read_bytes()
                if data[:8] == b"\x89PNG\r\n\x1a\n":
                    self._png_cache[size] = data
                    return data
            except Exception:
                pass
            finally:
                if os.path.exists(tmp_out):
                    os.unlink(tmp_out)

        # Portable zero-dependency pure-Python PNG decoder + premultiplied resampler.
        if self._decoded is None:
            self._decoded = _decode_png_rgba_stdlib(self.source_png)
        w, h, rgba = self._decoded
        resized_rgba = _resample_rgba_premult_stdlib(w, h, rgba, size)
        data = _encode_png_bytes(size, size, resized_rgba)
        self._png_cache[size] = data
        return data

    def write_resized_png(self, out_path: Path, size: int) -> None:
        out_path.parent.mkdir(parents=True, exist_ok=True)
        out_path.write_bytes(self.png_bytes_for_size(size))


def write_ico(out_path: Path, cache: _SourceRasterCache, sizes: Sequence[int] = ICO_SIZES) -> None:
    """Write a multi-resolution Windows .ico file embedding lossless PNG frames."""
    frames: list[tuple[int, bytes]] = [(sz, cache.png_bytes_for_size(sz)) for sz in sizes]
    out_path.parent.mkdir(parents=True, exist_ok=True)
    header = struct.pack("<HHH", 0, 1, len(frames))
    offset = 6 + 16 * len(frames)
    entries = bytearray()
    payload = bytearray()
    for sz, png_bytes in frames:
        dim = 0 if sz >= 256 else sz
        entries.extend(
            struct.pack("<BBBBHHII", dim, dim, 0, 0, 1, 32, len(png_bytes), offset)
        )
        payload.extend(png_bytes)
        offset += len(png_bytes)
    out_path.write_bytes(header + bytes(entries) + bytes(payload))


def write_icns(
    out_path: Path,
    cache: _SourceRasterCache,
    specs: Sequence[tuple[bytes, int]] = ICNS_SPECS,
) -> None:
    """Write a multi-resolution macOS .icns file embedding PNG icon chunks (cross-OS)."""
    chunks = bytearray()
    for tag, sz in specs:
        png_bytes = cache.png_bytes_for_size(sz)
        chunks.extend(tag)
        chunks.extend(struct.pack(">I", 8 + len(png_bytes)))
        chunks.extend(png_bytes)
    total_len = 8 + len(chunks)
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_bytes(b"icns" + struct.pack(">I", total_len) + bytes(chunks))


def export_branding_suite(
    output_dir: Path,
    sizes: Iterable[int] = BRANDING_SIZES,
    source_png: Optional[Path] = None,
    source_url: Optional[str] = None,
) -> None:
    """Export complete all-platform icon suite from the canonical remote logo URL."""
    resolved = resolve_source_png(
        explicit_source=str(source_png) if source_png is not None else None,
        explicit_url=source_url,
    )
    cache = _SourceRasterCache(resolved)
    output_dir.mkdir(parents=True, exist_ok=True)

    # 1. Root multi-size PNGs.
    for size in sizes:
        cache.write_resized_png(output_dir / f"euv-studio-logo-{size}.png", size)

    # 2. Desktop native icons (macOS .icns, Windows .ico, Linux PNGs).
    write_icns(output_dir / "macos" / "AppIcon.icns", cache)
    write_ico(output_dir / "windows" / "euv.ico", cache)
    cache.write_resized_png(output_dir / "linux" / "euv.png", 512)
    cache.write_resized_png(output_dir / "linux" / "euv-256.png", 256)
    cache.write_resized_png(output_dir / "linux" / "euv-128.png", 128)

    # 3. Web favicons and Apple touch icon.
    cache.write_resized_png(output_dir / "web" / "favicon.png", 64)
    cache.write_resized_png(output_dir / "web" / "favicon-32.png", 32)
    cache.write_resized_png(output_dir / "web" / "apple-touch-icon.png", 180)

    # 4. Android & Wear OS mipmap launcher icons.
    for density_dir, sz in ANDROID_MIPMAP_SPECS:
        cache.write_resized_png(output_dir / "android" / density_dir / "ic_launcher.png", sz)

    # 5. iOS & iPadOS AppIcon.appiconset.
    ios_dir = output_dir / "ios" / "AppIcon.appiconset"
    ios_images = []
    for filename, sz, pt_size, idiom, scale in IOS_ICON_SPECS:
        cache.write_resized_png(ios_dir / filename, sz)
        ios_images.append(
            {"filename": filename, "idiom": idiom, "scale": scale, "size": pt_size}
        )
    (ios_dir / "Contents.json").write_text(
        json.dumps({"images": ios_images, "info": {"author": "euv", "version": 1}}, indent=2)
        + "\n",
        encoding="utf-8",
    )

    # 6. Apple watchOS AppIcon.appiconset.
    watch_dir = output_dir / "watchos" / "AppIcon.appiconset"
    watch_images = []
    for filename, sz, pt_size, scale in WATCHOS_ICON_SPECS:
        cache.write_resized_png(watch_dir / filename, sz)
        watch_images.append(
            {"filename": filename, "idiom": "watch", "scale": scale, "size": pt_size}
        )
    (watch_dir / "Contents.json").write_text(
        json.dumps({"images": watch_images, "info": {"author": "euv", "version": 1}}, indent=2)
        + "\n",
        encoding="utf-8",
    )

    # 7. HarmonyOS, Wearables (vivo BlueOS / Vela / OPPO / Garmin / Zepp OS), MiniApp & QuickApp.
    cache.write_resized_png(output_dir / "harmony" / "app_icon.png", 192)
    cache.write_resized_png(output_dir / "wearable" / "logo.png", 192)
    cache.write_resized_png(output_dir / "miniapp" / "logo.png", 192)
    cache.write_resized_png(output_dir / "quickapp" / "logo.png", 192)


def _default_export_dir() -> Path:
    return _repo_root() / "target" / "euv-icon-export"


def main(argv: Optional[Sequence[str]] = None) -> int:
    args_list = list(sys.argv[1:] if argv is None else argv)

    if any(
        arg in ("--all", "--icns", "--ico", "--output-dir", "--source", "--url", "-h", "--help")
        for arg in args_list
    ):
        parser = argparse.ArgumentParser(
            description="Generate cross-platform Euv icons (PNG/ICO/ICNS) from the remote logo URL."
        )
        parser.add_argument(
            "--all",
            action="store_true",
            help="Export complete multi-platform icon suite into --output-dir.",
        )
        parser.add_argument(
            "--output-dir",
            type=Path,
            default=_default_export_dir(),
            help="Destination directory for --all exports (default: target/euv-icon-export).",
        )
        parser.add_argument(
            "--source",
            type=Path,
            default=None,
            help="Optional local master transparent RGBA PNG source override.",
        )
        parser.add_argument(
            "--url",
            type=str,
            default=None,
            help=f"Remote fallback PNG logo URL (default: {DEFAULT_LOGO_URL}).",
        )
        parser.add_argument(
            "--icns",
            type=Path,
            default=None,
            help="Write a multi-resolution macOS .icns bundle to the specified path.",
        )
        parser.add_argument(
            "--ico",
            type=Path,
            default=None,
            help="Write a multi-resolution Windows .ico file to the specified path.",
        )
        parsed = parser.parse_args(args_list)
        if parsed.all:
            export_branding_suite(
                parsed.output_dir,
                source_png=parsed.source,
                source_url=parsed.url,
            )
        if parsed.icns is not None or parsed.ico is not None:
            resolved = resolve_source_png(
                explicit_source=str(parsed.source) if parsed.source is not None else None,
                explicit_url=parsed.url,
            )
            cache = _SourceRasterCache(resolved)
            if parsed.icns is not None:
                write_icns(parsed.icns, cache)
            if parsed.ico is not None:
                write_ico(parsed.ico, cache)
        if not parsed.all and parsed.icns is None and parsed.ico is None:
            parser.print_help(sys.stderr)
            return 2
        return 0

    if len(args_list) < 2:
        sys.stderr.write(
            "Usage: generate-icon.py <output_png_or_ico_or_icns> <size_px> [custom_source_png_or_url]\n"
            "       generate-icon.py --all [--output-dir <dir>] [--source <png>] [--url <url>]\n"
            "       generate-icon.py --icns <output_icns> | --ico <output_ico>\n"
        )
        return 2

    out_path = Path(args_list[0])
    size = max(16, min(2048, int(args_list[1])))
    custom_src = args_list[2] if len(args_list) > 2 and args_list[2] else None
    resolved = resolve_source_png(explicit_source=custom_src)
    cache = _SourceRasterCache(resolved)
    suffix = out_path.suffix.lower()
    if suffix == ".ico":
        write_ico(out_path, cache)
    elif suffix == ".icns":
        write_icns(out_path, cache)
    else:
        cache.write_resized_png(out_path, size)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())