Private/FlutterFlavorAssets.ps1

# FlutterFlavorAssets.ps1
# Helpers de New-FlutterFlavorAssets: leer flavors.json y dibujar el ícono de cada ambiente.
# Usan System.Drawing (GDI+), que solo existe en Windows.

# Tamaños de los mipmaps de Android (ícono clásico, 48dp).
$script:FlavorMipmapSizes = [ordered]@{
    'mipmap-mdpi' = 48; 'mipmap-hdpi' = 72; 'mipmap-xhdpi' = 96; 'mipmap-xxhdpi' = 144; 'mipmap-xxxhdpi' = 192
}

function Read-FlutterFlavorConfig {
    # Lee y valida flavors.json. Devuelve nombre, ícono, salida Dart y la lista ordenada de flavors.
    param([Parameter(Mandatory)][string]$AppRoot)

    $file = Join-Path $AppRoot 'flavors.json'
    if (-not (Test-Path $file)) { throw "No existe $file. Créelo con 'nombre', 'icono' y 'flavors' (ver Get-Help New-FlutterFlavorAssets)." }
    $config = Get-Content $file -Raw -Encoding UTF8 | ConvertFrom-Json

    foreach ($key in 'nombre', 'icono', 'flavors') {
        if (-not $config.$key) { throw "flavors.json: falta la clave '$key'." }
    }
    $icono = Join-Path $AppRoot $config.icono
    if (-not (Test-Path $icono)) { throw "flavors.json: no existe el ícono '$($config.icono)'." }

    $flavors = foreach ($f in $config.flavors.PSObject.Properties) {
        $name = $f.Name
        # Mismo criterio que MACSS_FLUTTER_FLAVOR, en minúsculas: es sufijo del applicationId y
        # nombre de carpeta de Gradle.
        if ($name -cnotmatch '^[a-z][a-z0-9]*$') { throw "flavors.json: nombre de ambiente inválido '$name': minúsculas y dígitos, empezando por letra." }
        if ($name -eq 'prod') { throw "flavors.json: 'prod' no va en flavors: es la app sin sufijo ni etiqueta." }
        if (-not $f.Value.etiqueta) { throw "flavors.json: al ambiente '$name' le falta 'etiqueta'." }
        if ($f.Value.color -notmatch '^#[0-9A-Fa-f]{6}$') { throw "flavors.json: el color de '$name' debe ser #RRGGBB (es '$($f.Value.color)')." }
        [pscustomobject]@{ Name = $name; Etiqueta = [string]$f.Value.etiqueta; Color = $f.Value.color.ToUpper() }
    }

    [pscustomobject]@{
        Nombre  = [string]$config.nombre
        Icono   = $icono
        Dart    = if ($config.dart) { [string]$config.dart } else { 'lib/app/ambientes.g.dart' }
        Flavors = @($flavors)
    }
}

function New-FlavorRoundedRect {
    param([System.Drawing.RectangleF]$Rect, [float]$Radius)
    $p = [System.Drawing.Drawing2D.GraphicsPath]::new()
    $d = $Radius * 2
    $p.AddArc($Rect.X, $Rect.Y, $d, $d, 180, 90)
    $p.AddArc($Rect.Right - $d, $Rect.Y, $d, $d, 270, 90)
    $p.AddArc($Rect.Right - $d, $Rect.Bottom - $d, $d, $d, 0, 90)
    $p.AddArc($Rect.X, $Rect.Bottom - $d, $d, $d, 90, 90)
    $p.CloseFigure()
    return $p
}

function New-FlavorIconBitmap {
    # Ícono de 1024 px: el de prod con una etiqueta de color centrada abajo. Va centrada y no en una
    # esquina porque cada launcher recorta el ícono con su forma (Samsung redondea las esquinas,
    # Pixel lo hace círculo); también sube un poco para quedar dentro del círculo.
    param(
        [Parameter(Mandatory)][string]$BaseIcon,
        [Parameter(Mandatory)][string]$Etiqueta,
        [Parameter(Mandatory)][string]$ColorHex,
        [Parameter(Mandatory)][System.Drawing.FontFamily]$Family,
        [System.Drawing.FontStyle]$Style = [System.Drawing.FontStyle]::Regular
    )
    $n = 1024
    $bmp = [System.Drawing.Bitmap]::new($n, $n)
    $g = [System.Drawing.Graphics]::FromImage($bmp)
    try {
        $g.SmoothingMode = 'AntiAlias'; $g.InterpolationMode = 'HighQualityBicubic'; $g.TextRenderingHint = 'AntiAlias'
        $base = [System.Drawing.Image]::FromFile($BaseIcon)
        try { $g.DrawImage($base, 0, 0, $n, $n) } finally { $base.Dispose() }

        $h = 220; $marginX = 170; $marginBottom = 140; $pad = 40; $maxW = $n - 2 * $marginX
        # Más grande que ~74% del alto y GDI+ no dibuja el texto: no cabe en la etiqueta.
        $size = [int]($h * 0.74)
        $typo = [System.Drawing.StringFormat]::GenericTypographic
        do {
            $font = [System.Drawing.Font]::new($Family, $size, $Style, [System.Drawing.GraphicsUnit]::Pixel)
            $tw = $g.MeasureString($Etiqueta, $font, [System.Drawing.PointF]::new(0, 0), $typo).Width
            if ($tw + 2 * $pad -le $maxW -or $size -le 60) { break }
            $font.Dispose(); $size -= 6
        } while ($true)
        $w = [math]::Min([math]::Max($tw + 2 * $pad, $h * 1.6), $maxW)
        $rect = [System.Drawing.RectangleF]::new(($n - $w) / 2, $n - $marginBottom - $h, $w, $h)

        $path = New-FlavorRoundedRect -Rect $rect -Radius 52
        $fill = [System.Drawing.SolidBrush]::new([System.Drawing.ColorTranslator]::FromHtml($ColorHex))
        $pen = [System.Drawing.Pen]::new([System.Drawing.Color]::White, 14)
        $ink = [System.Drawing.SolidBrush]::new([System.Drawing.ColorTranslator]::FromHtml('#1A1A1A'))
        $fmt = [System.Drawing.StringFormat]::new($typo)
        try {
            $g.FillPath($fill, $path)
            $g.DrawPath($pen, $path)
            $fmt.Alignment = 'Center'; $fmt.LineAlignment = 'Center'
            $fmt.FormatFlags = $fmt.FormatFlags -bor [System.Drawing.StringFormatFlags]::NoClip -bor [System.Drawing.StringFormatFlags]::NoWrap
            $text = [System.Drawing.RectangleF]::new($rect.X, $rect.Y + $h * 0.04, $rect.Width, $rect.Height)
            $g.DrawString($Etiqueta, $font, $ink, $text, $fmt)
        } finally {
            $font.Dispose(); $fill.Dispose(); $pen.Dispose(); $ink.Dispose(); $fmt.Dispose(); $path.Dispose()
        }
    } finally { $g.Dispose() }
    return $bmp
}

function Save-FlavorIconResized {
    param([System.Drawing.Bitmap]$Source, [int]$Pixels, [string]$Path)
    New-Item -ItemType Directory -Force (Split-Path $Path) | Out-Null
    $dst = [System.Drawing.Bitmap]::new($Pixels, $Pixels)
    $g = [System.Drawing.Graphics]::FromImage($dst)
    try {
        $g.InterpolationMode = 'HighQualityBicubic'; $g.SmoothingMode = 'AntiAlias'; $g.PixelOffsetMode = 'HighQuality'
        $g.DrawImage($Source, 0, 0, $Pixels, $Pixels)
    } finally { $g.Dispose() }
    try { $dst.Save($Path, [System.Drawing.Imaging.ImageFormat]::Png) } finally { $dst.Dispose() }
}

function ConvertTo-FlavorDart {
    # Contenido de ambientes.g.dart: ambientes válidos y color de la cinta de cada uno.
    param([Parameter(Mandatory)][object[]]$Flavors)
    $validos = (@('prod') + @($Flavors.Name) | ForEach-Object { "'$_'" }) -join ', '
    $colores = ($Flavors | ForEach-Object { " '$($_.Name)': Color(0xFF$($_.Color.TrimStart('#')))," }) -join "`n"
    return @"
// GENERADO por New-FlutterFlavorAssets (macss-devops) desde flavors.json. No editar a mano.
import 'dart:ui';
 
/// Valores válidos de AMBIENTE: prod y los ambientes de flavors.json.
const ambientesValidos = {$validos};
 
/// Color de la cinta de cada ambiente: el mismo de la etiqueta de su ícono.
const coloresDeAmbiente = {
$colores
};
 
"@
 -replace "`r`n", "`n"
}