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
DEFAULT_LOGO_URL: str = "https://devhub.vip/pages/docs/img/euv.png"
BRANDING_SIZES: tuple[int, ...] = (1024, 512, 256, 192, 180, 128, 64, 32)
ICO_SIZES: tuple[int, ...] = (16, 32, 48, 64, 128, 256)
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_MIPMAP_SPECS: tuple[tuple[str, int], ...] = (
("mipmap-mdpi", 48),
("mipmap-hdpi", 72),
("mipmap-xhdpi", 96),
("mipmap-xxhdpi", 144),
("mipmap-xxxhdpi", 192),
)
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"),
)
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]:
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:
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:
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:
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]:
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:
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:
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
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
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)
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:
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:
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:
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)
for size in sizes:
cache.write_resized_png(output_dir / f"euv-studio-logo-{size}.png", size)
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)
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)
for density_dir, sz in ANDROID_MIPMAP_SPECS:
cache.write_resized_png(output_dir / "android" / density_dir / "ic_launcher.png", sz)
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",
)
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",
)
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())