Public/DrawIconPack.ps1
|
#Requires -Version 7.0 # ============================================================ # DrawManagement — user icon packs # # draw.io ships no modern VMware set, and vendor artwork (VMware's official # stencils, a company icon set, the ~1,000 extra sets hosted on # icons.diagrams.net — Fortinet, Commvault, Arista, ...) usually carries no # licence that allows it to be redistributed inside this module. These # cmdlets let each user install such a set into their OWN profile and place # icons from it by name. Only the code ships; the artwork stays wherever the # user got it from. # # Each placed icon is embedded in the diagram as a data URI (a few KB), so # the .drawio opens anywhere without the pack installed — or, with # Add-DrawPackIcon -Reference, linked to its remote URL as draw.io does. # ============================================================ function Install-DrawIconPack { <# .SYNOPSIS Installs an icon set — a folder/zip of SVGs, a draw.io library, or a set from icons.diagrams.net — as a named icon pack in your profile. .DESCRIPTION Stores the icons, normalised, with a manifest in <LocalApplicationData>/DrawManagement/IconPacks/<Name>/ (override with $env:DRAWMANAGEMENT_ICONPACKS). Nothing is written into the module folder, and nothing is shipped with the module. Four sources: -Path a folder or .zip of SVG files (recursive) -Uri a .zip to download (e.g. a GitHub archive) -Library a draw.io library file (<mxlibrary>, the .xml from File > Open Library / Export-DrawStencilLibrary), local path or URL -DiagramsNetSet a set from https://icons.diagrams.net by its name (Find-DrawIconSet) — ~1,000 extra sets that are NOT bundled with draw.io: Fortinet, Commvault, Arista, IBM Carbon, Material Symbols, Kubernetes, ... Library entries may be SVG or raster images (embedded or referenced by URL — referenced ones are downloaded once, a few at a time), or a single styled cell such as a Commvault badge. Composite drawings of several cells are skipped and counted. SVGs are measured from their viewBox and cropped when the artwork sits small on a page-sized artboard behind one clip rectangle. -Color only records the pack's default for Add-DrawPackIcon, which recolours SVGs at placement time. Icon names come from the file name or library title: lower-cased, spaces turned into '-'. Duplicates get a folder prefix (files) or a numeric suffix (libraries). LICENCES DIFFER PER SET. For icons.diagrams.net the set's licence and author are read from its page, stored in the manifest, shown by Get-DrawIconPack, and a warning is printed when no licence is published. Using icons in your own diagrams is what vendor sets are published for; redistributing the files usually is not. .PARAMETER Name Pack name, used by Add-DrawPackIcon -Pack. Letters, digits, '_' and '-'. Defaults to the set name with -DiagramsNetSet. .PARAMETER Path A folder or a .zip containing SVG files. .PARAMETER Uri URL of a .zip to download, e.g. a GitHub 'archive/refs/heads/main.zip'. .PARAMETER Library A draw.io library file (.xml with an <mxlibrary> root): path or URL. .PARAMETER DiagramsNetSet Set name on icons.diagrams.net, as in https://icons.diagrams.net/sets/<name>. .PARAMETER Color Default colour (#RGB or #RRGGBB) Add-DrawPackIcon applies to this pack's SVG icons. Omit to keep the artwork's own colours — usually right for full-colour vendor sets. .PARAMETER Filter Wildcard on the SVG file name for -Path/-Uri. Default: '*.svg'. .PARAMETER Force Replace an existing pack with the same name. .PARAMETER PassThru Return the installed pack (as Get-DrawIconPack shows it). .EXAMPLE # VMware's official icon set, in VMware blue Install-DrawIconPack -Name vmware -Color '#0091DA' ` -Uri 'https://github.com/h0bbel/vmware-stencils/archive/refs/heads/main.zip' .EXAMPLE # Extra sets hosted by draw.io Find-DrawIconSet -Name fortinet Install-DrawIconPack -DiagramsNetSet fortinet-products Install-DrawIconPack -DiagramsNetSet cvlt-infrastructure -Name commvault .EXAMPLE Install-DrawIconPack -Name corp -Library '\\share\brand\corp-library.xml' .OUTPUTS [PSCustomObject] when -PassThru is specified. #> [CmdletBinding(DefaultParameterSetName = 'Path')] [OutputType([PSCustomObject])] param( [Parameter(Mandatory, ParameterSetName = 'Path')] [Parameter(Mandatory, ParameterSetName = 'Uri')] [Parameter(Mandatory, ParameterSetName = 'Library')] [Parameter(ParameterSetName = 'DiagramsNet')] [ValidatePattern('^[A-Za-z0-9_\-]+$')][string] $Name, [Parameter(Mandatory, ParameterSetName = 'Path')][string] $Path, [Parameter(Mandatory, ParameterSetName = 'Uri')][uri] $Uri, [Parameter(Mandatory, ParameterSetName = 'Library')][string] $Library, [Parameter(Mandatory, ParameterSetName = 'DiagramsNet')] [ValidatePattern('^[A-Za-z0-9_.\-]+$')][string] $DiagramsNetSet, [Parameter()][string] $Color, [Parameter(ParameterSetName = 'Path')] [Parameter(ParameterSetName = 'Uri')][string] $Filter = '*.svg', [Parameter()][switch] $Force, [Parameter()][switch] $PassThru ) if (-not [string]::IsNullOrWhiteSpace($Color)) { Assert-HexColor -Color $Color -ParamName 'Color' } if ($PSCmdlet.ParameterSetName -eq 'DiagramsNet' -and [string]::IsNullOrWhiteSpace($Name)) { $Name = $DiagramsNetSet -replace '[^A-Za-z0-9_\-]', '-' } $root = Get-DrawIconPackRoot $packDir = Join-Path $root $Name if ((Test-Path -LiteralPath $packDir) -and -not $Force) { throw "Install-DrawIconPack: pack '$Name' is already installed at '$packDir'. Use -Force to replace it." } $work = Join-Path ([System.IO.Path]::GetTempPath()) ("drawiconpack-" + [guid]::NewGuid().ToString('N')) $stage = $null $null = New-Item -ItemType Directory -Path $work -Force try { $meta = [ordered]@{ title = ''; license = ''; author = ''; authorUrl = ''; page = '' } # Each item: Title, Kind (svg|png|jpeg|gif|style), File, Data, Url, Style, Value, W, H, FromFile $items = New-Object System.Collections.Generic.List[object] if ($PSCmdlet.ParameterSetName -in 'Path', 'Uri') { if ($PSCmdlet.ParameterSetName -eq 'Uri') { if (-not $Uri.IsAbsoluteUri -or $Uri.Scheme -notin 'http', 'https') { throw "Install-DrawIconPack: -Uri must be an absolute http(s) URL ('$Uri'). For a local file use -Path." } if ($Uri.Scheme -eq 'http') { Write-Warning 'Install-DrawIconPack: downloading over plain http — the content can be altered in transit. Prefer https.' } $zip = Join-Path $work 'source.zip' Write-Verbose "Install-DrawIconPack: downloading $Uri" Invoke-WebRequest -Uri $Uri -OutFile $zip -UseBasicParsing -TimeoutSec 600 -ErrorAction Stop $srcDir = Join-Path $work 'src' Expand-Archive -LiteralPath $zip -DestinationPath $srcDir -Force $source = $Uri.AbsoluteUri } else { $full = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).ProviderPath if (Test-Path -LiteralPath $full -PathType Leaf) { if ([System.IO.Path]::GetExtension($full) -ne '.zip') { throw ("Install-DrawIconPack: '$Path' is a file but not a .zip. " + 'For a draw.io library .xml use -Library.') } $srcDir = Join-Path $work 'src' Expand-Archive -LiteralPath $full -DestinationPath $srcDir -Force } else { $srcDir = $full } $source = $full } $files = @(Get-ChildItem -LiteralPath $srcDir -Recurse -File -Filter $Filter | Where-Object { $_.Extension -eq '.svg' -and $_.FullName -notmatch '[\\/]__MACOSX[\\/]' } | Sort-Object FullName) if ($files.Count -eq 0) { throw ("Install-DrawIconPack: no SVG files matching '$Filter' under the source. " + 'For a Visio .vssx use Import-DrawStencilFromVssx; for a draw.io library use -Library.') } foreach ($f in $files) { $items.Add([PSCustomObject]@{ Title = $f.BaseName; Folder = $f.Directory.Name; Kind = 'svg'; File = $f.FullName Data = $null; Url = ''; Style = ''; Value = ''; W = 0; H = 0; FromFile = $true }) } } else { # ── draw.io library: from icons.diagrams.net or a given file/URL ── if ($PSCmdlet.ParameterSetName -eq 'DiagramsNet') { $info = Get-DrawDiagramsNetSetInfo -Slug $DiagramsNetSet $libRef = $info.Library $source = $info.Page $meta.title = $info.Title; $meta.license = $info.License $meta.author = $info.Author; $meta.authorUrl = $info.AuthorUrl; $meta.page = $info.Page if ($info.License -match '(?i)none|no formal|unknown' -or [string]::IsNullOrWhiteSpace($info.License)) { Write-Warning ("Install-DrawIconPack: '$($info.Title)' has no published licence " + "($($info.License)). Fine for your own diagrams; do not redistribute the icons.") } } else { $libRef = $Library; $source = $Library } if ($libRef -match '^https?://') { if ($libRef -like 'http://*') { Write-Warning 'Install-DrawIconPack: downloading over plain http — the content can be altered in transit. Prefer https.' } Write-Verbose "Install-DrawIconPack: downloading $libRef" $libText = (Invoke-WebRequest -Uri $libRef -UseBasicParsing -TimeoutSec 60 -ErrorAction Stop).Content if ($libText -is [byte[]]) { $libText = [Text.Encoding]::UTF8.GetString($libText) } } else { $libPath = (Resolve-Path -LiteralPath $libRef -ErrorAction Stop).ProviderPath $libText = Get-Content -LiteralPath $libPath -Raw $source = $libPath } $entries = @(Read-DrawLibraryEntry -Text $libText) $skipped = @($entries | Where-Object Kind -eq 'skip').Count $n = 0 $downloads = New-Object System.Collections.Generic.List[object] foreach ($e in $entries | Where-Object Kind -ne 'skip') { $n++ $item = [PSCustomObject]@{ Title = $e.Title; Folder = ''; Kind = $e.Kind; File = ''; Data = $e.Data; Url = $e.Url Style = $e.Style; Value = $e.Value; W = $e.W; H = $e.H; FromFile = $false } if ($e.Url) { $item.File = Join-Path $work ("dl-{0:00000}.{1}" -f $n, $e.Kind) $downloads.Add([PSCustomObject]@{ Url = $e.Url; Path = $item.File }) } $items.Add($item) } if ($downloads.Count -gt 0) { Write-Verbose "Install-DrawIconPack: downloading $($downloads.Count) icon(s)" $failed = @(Invoke-DrawIconDownload -Item $downloads.ToArray()) if ($failed.Count -gt 0) { Write-Warning "Install-DrawIconPack: $($failed.Count) icon(s) could not be downloaded and were skipped." $bad = @{}; foreach ($x in $failed) { $bad[$x.Path] = $true } $items = [System.Collections.Generic.List[object]]@($items | Where-Object { -not $_.File -or -not $bad.ContainsKey($_.File) }) } } if ($skipped -gt 0) { Write-Warning "Install-DrawIconPack: $skipped library entr$(if ($skipped -eq 1) {'y is a'} else {'ies are'}) multi-cell drawing(s), not icons — skipped." } if ($items.Count -eq 0) { throw 'Install-DrawIconPack: the library holds no importable icons.' } } # ── Normalise into a staging folder beside the target, then swap in # (same volume, so the final Move-Item is a rename) ──────────── $null = New-Item -ItemType Directory -Path $root -Force $stage = Join-Path $root (".staging-" + [guid]::NewGuid().ToString('N')) $stageIco = Join-Path $stage 'icons' $null = New-Item -ItemType Directory -Path $stageIco -Force $icons = New-Object System.Collections.Generic.List[object] $seen = @{} $cropped = 0 $rejected = 0 # not the image they claim to be $stripped = 0 # SVGs that carried active content foreach ($it in $items) { # ── Check the content first — a rejected entry must not take a name $kind = $it.Kind $norm = $null $bytes = $null if ($kind -eq 'svg') { $text = if ($it.File) { Get-Content -LiteralPath $it.File -Raw } else { [Text.Encoding]::UTF8.GetString($it.Data) } $norm = ConvertTo-DrawNormalizedSvg -Text ([string]$text) if (-not $norm.Valid) { $rejected++; continue } } elseif ($kind -ne 'style') { $bytes = if ($it.File) { [System.IO.File]::ReadAllBytes($it.File) } else { $it.Data } $kind = Get-DrawImageKind -Bytes $bytes if (-not $kind) { $rejected++; continue } } $base = ConvertTo-DrawIconFileName -Title $it.Title $iconName = $base if ($seen.ContainsKey($iconName)) { if ($it.FromFile) { $iconName = (($it.Folder.ToLowerInvariant() -replace '[^a-z0-9_\-]', '_') + '-' + $base) } else { $k = 2; while ($seen.ContainsKey("$base-$k")) { $k++ }; $iconName = "$base-$k" } } if ($seen.ContainsKey($iconName)) { continue } $seen[$iconName] = $true $entry = [ordered]@{ name = $iconName; type = $kind; w = 0; h = 0 } if ($it.Title -ne $iconName) { $entry.title = $it.Title } if ($it.Url) { $entry.url = $it.Url } if ($kind -eq 'svg') { if ($norm.Cropped) { $cropped++ } if ($norm.Stripped -gt 0) { $stripped++ } Set-Content -LiteralPath (Join-Path $stageIco "$iconName.svg") -Value $norm.Svg -Encoding utf8NoBOM # Library entries carry draw.io's intended size; keep it unless cropped if ($it.FromFile -or $norm.Cropped -or $it.W -le 0) { $entry.w = $norm.Width; $entry.h = $norm.Height } else { $entry.w = $it.W; $entry.h = $it.H } } elseif ($kind -eq 'style') { $entry.style = $it.Style $entry.label = $it.Value $entry.w = $it.W; $entry.h = $it.H } else { [System.IO.File]::WriteAllBytes((Join-Path $stageIco "$iconName.$kind"), $bytes) $entry.w = $it.W; $entry.h = $it.H } $entry.w = [Math]::Round([double]$entry.w, 2) $entry.h = [Math]::Round([double]$entry.h, 2) $icons.Add($entry) } if ($rejected -gt 0) { Write-Warning ("Install-DrawIconPack: $rejected entr$(if ($rejected -eq 1) {'y is'} else {'ies are'}) " + 'not the image the source claims (not an SVG document / not a PNG, JPEG or GIF) — skipped.') } if ($stripped -gt 0) { Write-Warning ("Install-DrawIconPack: $stripped SVG icon(s) carried scripts or event handlers; " + 'these were removed. Treat the source with care.') } # Before the swap: -Force must never replace a working pack with an empty one if ($icons.Count -eq 0) { throw 'Install-DrawIconPack: the source holds no usable icons — nothing was installed.' } $manifest = [ordered]@{ name = $Name source = $source installed = [datetime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ', [cultureinfo]::InvariantCulture) color = $Color title = $meta.title license = $meta.license author = $meta.author authorUrl = $meta.authorUrl page = $meta.page icons = $icons } $manifest | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath (Join-Path $stage 'pack.json') -Encoding utf8NoBOM if (Test-Path -LiteralPath $packDir) { Remove-Item -LiteralPath $packDir -Recurse -Force } Move-Item -LiteralPath $stage -Destination $packDir $stage = $null # Placement cache may hold icons from a replaced pack foreach ($k in @($script:DrawIconPackCache.Keys)) { if ($k -like "$Name|*") { $script:DrawIconPackCache.Remove($k) } } Write-Verbose ("Install-DrawIconPack: '$Name' — $($icons.Count) icons" + $(if ($cropped) { ", $cropped cropped to their clip rectangle" } else { '' }) + " -> $packDir") } finally { Remove-Item -LiteralPath $work -Recurse -Force -ErrorAction SilentlyContinue if ($stage) { Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue } } if ($PassThru) { return (Get-DrawIconPack -Name $Name) } } function Find-DrawIconSet { <# .SYNOPSIS Searches the extra icon sets hosted on icons.diagrams.net. .DESCRIPTION icons.diagrams.net hosts ~1,000 icon sets that are NOT bundled with draw.io — vendor sets (Fortinet, Commvault, Arista, OCI, IBM Carbon, GitLab, Kubernetes, an extra Azure integration set) and general ones (Material Symbols, Font Awesome, Tabler, flags, ...). Returns set names to pass to Install-DrawIconPack -DiagramsNetSet. Names come from the site's sitemap (read once per session). With -Detailed each match's page is read for its title, icon count, licence and author — one request per set, so narrow -Name first. .PARAMETER Name Wildcard on the set name. Bare text matches anywhere ('forti' is '*forti*'). .PARAMETER Detailed Also read each matching set's page: Title, Icons, License, Author. .EXAMPLE Find-DrawIconSet -Name fortinet .EXAMPLE Find-DrawIconSet -Name cvlt -Detailed | Format-Table Name, Icons, License .OUTPUTS [PSCustomObject] Name, Url (+ Title, Icons, License, Author with -Detailed). #> [CmdletBinding()] [OutputType([PSCustomObject])] param( [Parameter(Position = 0)][string] $Name = '*', [Parameter()][switch] $Detailed ) if ($null -eq $script:DrawDiagramsNetSets) { try { $sm = [xml](Invoke-WebRequest -Uri "$script:DrawDiagramsNetRoot/sitemap.xml" -UseBasicParsing -TimeoutSec 60 -ErrorAction Stop).Content } catch { throw "Find-DrawIconSet: could not read $script:DrawDiagramsNetRoot/sitemap.xml — $($_.Exception.Message)" } $script:DrawDiagramsNetSets = @( $sm.DocumentElement.ChildNodes | Where-Object { $_ -is [System.Xml.XmlElement] } | ForEach-Object { $_.ChildNodes | Where-Object { $_ -is [System.Xml.XmlElement] -and $_.LocalName -eq 'loc' } | Select-Object -First 1 | ForEach-Object { $_.InnerText.Trim() } } | Where-Object { $_ -match '/sets/([^/?#]+)$' } | ForEach-Object { ($_ -split '/sets/')[1] } | Sort-Object -Unique ) } $pattern = if ($Name -match '[\*\?]') { $Name } else { "*$Name*" } $hits = @($script:DrawDiagramsNetSets | Where-Object { $_ -like $pattern }) if ($Detailed -and $hits.Count -gt 40) { Write-Warning "Find-DrawIconSet: $($hits.Count) sets match — -Detailed reads one page per set; narrow -Name first." return } foreach ($s in $hits) { if ($Detailed) { $i = Get-DrawDiagramsNetSetInfo -Slug $s [PSCustomObject]@{ PSTypeName = 'DrawManagement.IconSet' Name = $s; Title = $i.Title; Icons = $i.Icons; License = $i.License; Author = $i.Author; Url = $i.Page } } else { [PSCustomObject]@{ PSTypeName = 'DrawManagement.IconSet' Name = $s; Url = "$script:DrawDiagramsNetRoot/sets/$s" } } } } function Get-DrawIconPack { <# .SYNOPSIS Lists installed icon packs, or the icons inside them. .DESCRIPTION Without -Icon, returns one object per pack: Name, Icons (count), Title, License, Author (filled for icons.diagrams.net sets), Color, Source, Installed, Path. With -Icon, returns the matching icons: Pack, Name, Type (svg, png, jpeg, gif or style), Width, Height, Url (the remote original, if any), Path — the names to pass to Add-DrawPackIcon. .PARAMETER Name Wildcard on the pack name. Default: all packs. .PARAMETER Icon Wildcard on the icon name. Bare text matches anywhere ('nsx' is '*nsx*'). .EXAMPLE Get-DrawIconPack .EXAMPLE Get-DrawIconPack -Name vmware -Icon 'vcenter' .OUTPUTS [PSCustomObject] #> [CmdletBinding()] [OutputType([PSCustomObject])] param( [Parameter(Position = 0)][string] $Name = '*', [Parameter()][string] $Icon ) $root = Get-DrawIconPackRoot if (-not (Test-Path -LiteralPath $root)) { return } foreach ($dir in @(Get-ChildItem -LiteralPath $root -Directory | Where-Object { $_.Name -like $Name -and -not $_.Name.StartsWith('.') } | Sort-Object Name)) { $m = Read-DrawIconPackManifest -PackDir $dir.FullName if ($null -eq $m) { continue } if ([string]::IsNullOrWhiteSpace($Icon)) { [PSCustomObject]@{ PSTypeName = 'DrawManagement.IconPack' Name = $dir.Name Icons = @($m.icons).Count Title = Get-DrawObjectProperty -InputObject $m -Name 'title' -Default '' License = Get-DrawObjectProperty -InputObject $m -Name 'license' -Default '' Author = Get-DrawObjectProperty -InputObject $m -Name 'author' -Default '' Color = $m.color Source = $m.source Installed = $m.installed Path = $dir.FullName } continue } $pattern = if ($Icon -match '[\*\?]') { $Icon } else { "*$Icon*" } foreach ($i in @($m.icons | Where-Object { $_.name -like $pattern })) { $type = Get-DrawObjectProperty -InputObject $i -Name 'type' -Default 'svg' [PSCustomObject]@{ PSTypeName = 'DrawManagement.IconPackIcon' Pack = $dir.Name Name = $i.name Type = $type Width = [double]$i.w Height = [double]$i.h Url = Get-DrawObjectProperty -InputObject $i -Name 'url' -Default '' Path = if ($type -eq 'style') { '' } else { Join-Path $dir.FullName 'icons' "$($i.name).$type" } } } } } function Uninstall-DrawIconPack { <# .SYNOPSIS Removes an installed icon pack from your profile. .DESCRIPTION Deletes the pack's folder. Diagrams already saved are unaffected: every placed icon was embedded in the .drawio when it was added. .PARAMETER Name Pack name, as listed by Get-DrawIconPack. .EXAMPLE Uninstall-DrawIconPack -Name vmware .OUTPUTS None #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] param( [Parameter(Mandatory, Position = 0, ValueFromPipelineByPropertyName)] [ValidatePattern('^[A-Za-z0-9_\-]+$')][string] $Name ) process { $packDir = Join-Path (Get-DrawIconPackRoot) $Name if (-not (Test-Path -LiteralPath $packDir)) { throw "Uninstall-DrawIconPack: no icon pack named '$Name' is installed." } if ($PSCmdlet.ShouldProcess($packDir, 'Remove icon pack')) { Remove-Item -LiteralPath $packDir -Recurse -Force foreach ($k in @($script:DrawIconPackCache.Keys)) { if ($k -like "$Name|*") { $script:DrawIconPackCache.Remove($k) } } } } } function Add-DrawPackIcon { <# .SYNOPSIS Places an icon from an installed icon pack onto a page. .DESCRIPTION Embeds the icon as an image data URI, so the saved diagram does not depend on the pack being installed where it is opened. The label sits below the icon. Icons keep their aspect ratio: -Size fits the longest side (default 48 px). Colour: -Color, else the pack's default from Install-DrawIconPack -Color, else the artwork's own colours. Recolouring replaces every non-white fill/stroke of an SVG, which suits single-colour vendor glyphs; use -KeepColors for multi-colour artwork. Raster icons (png/jpeg/gif) cannot be recoloured. Style entries (a single styled cell from a draw.io library, such as a Commvault badge) are placed with draw.io's own style, text and size; -Color sets their fill. -Reference links the remote original (icons.diagrams.net sets and URL-based libraries) instead of embedding it — exactly what draw.io does when you drag from such a library. The file stays tiny, but the icon only renders when the viewer can reach that URL. .PARAMETER Page The [DrawPage] to add the icon to. .PARAMETER Pack Installed pack name (Get-DrawIconPack). .PARAMETER Icon Icon name within the pack (Get-DrawIconPack -Name <pack> -Icon <text>). .PARAMETER Label Text under the icon. HTML (<br>, <b>) is allowed. .PARAMETER X Left position. Default: 100. .PARAMETER Y Top position. Default: 100. .PARAMETER Size Longest side in pixels, keeping the aspect ratio. Default: 48. .PARAMETER Width Explicit width. Given alone, the height follows the aspect ratio. .PARAMETER Height Explicit height. Given alone, the width follows the aspect ratio. .PARAMETER Color Recolour the icon (#RGB or #RRGGBB). Overrides the pack default. .PARAMETER KeepColors Use the artwork's own colours, ignoring -Color and the pack default. .PARAMETER Reference Link the icon's remote URL instead of embedding it. Only for icons installed from a URL-based library (e.g. -DiagramsNetSet); cannot be combined with -Color. .PARAMETER ParentId Parent container id. Default: '1'. .PARAMETER Metadata UserObject properties. .PARAMETER Tooltip Hover text. .PARAMETER PassThru Return the created [DrawCell]. .EXAMPLE $vc = Add-DrawPackIcon -Page $p -Pack vmware -Icon vcenter-server ` -Label 'vcsa01' -X 200 -Y 120 -PassThru .EXAMPLE Add-DrawPackIcon -Page $p -Pack vmware -Icon vmware-vsan -Size 64 -Color '#717074' .EXAMPLE # icons.diagrams.net set, linked rather than embedded Add-DrawPackIcon -Page $p -Pack fortinet-products -Icon fortigate-base-dark -Reference .OUTPUTS [DrawCell] when -PassThru is specified. #> [CmdletBinding()] [OutputType([DrawCell])] param( [Parameter(Mandatory)][DrawPage] $Page, [Parameter(Mandatory)][ValidatePattern('^[A-Za-z0-9_\-]+$')][string] $Pack, [Parameter(Mandatory, Position = 0)][ValidateNotNullOrEmpty()][string] $Icon, [Parameter()][string] $Label = '', [Parameter()][ValidateRange(0, 99999)][double] $X = 100, [Parameter()][ValidateRange(0, 99999)][double] $Y = 100, [Parameter()][ValidateRange(1, 99999)][double] $Size, [Parameter()][ValidateRange(1, 99999)][double] $Width, [Parameter()][ValidateRange(1, 99999)][double] $Height, [Parameter()][string] $Color, [Parameter()][switch] $KeepColors, [Parameter()][switch] $Reference, [Parameter()][string] $ParentId = '1', [Parameter()][hashtable] $Metadata = @{}, [Parameter()][string] $Tooltip, [Parameter()][switch] $PassThru ) if ($PSBoundParameters.ContainsKey('Size') -and ($PSBoundParameters.ContainsKey('Width') -or $PSBoundParameters.ContainsKey('Height'))) { throw 'Add-DrawPackIcon: -Size cannot be combined with -Width or -Height.' } if (-not [string]::IsNullOrWhiteSpace($Color)) { Assert-HexColor -Color $Color -ParamName 'Color' } $packDir = Join-Path (Get-DrawIconPackRoot) $Pack $m = Read-DrawIconPackManifest -PackDir $packDir if ($null -eq $m) { $have = @(Get-DrawIconPack | ForEach-Object Name) $hint = if ($have.Count) { " Installed: $($have -join ', ')." } else { ' No packs are installed.' } throw ("Add-DrawPackIcon: icon pack '$Pack' is not installed.$hint " + 'Install one with Install-DrawIconPack.') } $entry = $m.icons | Where-Object { $_.name -eq $Icon } | Select-Object -First 1 if ($null -eq $entry) { $near = @($m.icons | Where-Object { $_.name -like "*$Icon*" } | Select-Object -First 5 | ForEach-Object name) $hint = if ($near.Count) { " Did you mean: $($near -join ', ')?" } else { '' } throw ("Add-DrawPackIcon: '$Icon' is not in pack '$Pack'.$hint " + "List icons with Get-DrawIconPack -Name $Pack -Icon <text>.") } $type = Get-DrawObjectProperty -InputObject $entry -Name 'type' -Default 'svg' $url = Get-DrawObjectProperty -InputObject $entry -Name 'url' -Default '' # The manifest is a file in the user's profile; it decides a path below, # so hold it to what Install-DrawIconPack itself writes. if ($type -notin 'svg', 'png', 'jpeg', 'gif', 'style' -or $Icon -notmatch '^[A-Za-z0-9_.\-]+$') { throw ("Add-DrawPackIcon: pack '$Pack' has an invalid manifest entry for '$Icon' " + "(type '$type'). Reinstall the pack.") } $natW = [double]$entry.w $natH = [double]$entry.h $hasColor = -not [string]::IsNullOrWhiteSpace($Color) if ($type -eq 'style') { # A styled cell (e.g. a Commvault badge): draw.io's own style, its own # text unless -Label is given, its own size unless one is given. $style = [string]$entry.style if ($hasColor) { $style = Join-DrawStyle $style "fillColor=$Color;" } if (-not $PSBoundParameters.ContainsKey('Label')) { $Label = [string](Get-DrawObjectProperty -InputObject $entry -Name 'label' -Default '') } $dim = if ($Size -gt 0 -or $Width -gt 0 -or $Height -gt 0) { Get-DrawFitSize -NaturalWidth $natW -NaturalHeight $natH -Size $Size -Width $Width -Height $Height } else { [PSCustomObject]@{ Width = $natW; Height = $natH } } } else { if ($Reference) { if (-not $url) { throw ("Add-DrawPackIcon: '$Icon' in pack '$Pack' has no remote original to reference " + '(it was installed from local files). Omit -Reference to embed it.') } if ($hasColor) { throw 'Add-DrawPackIcon: a referenced image cannot be recoloured; omit -Color or -Reference.' } $imageRef = $url } else { $useColor = '' if ($type -eq 'svg' -and -not $KeepColors) { $useColor = if ($hasColor) { $Color } else { [string](Get-DrawObjectProperty -InputObject $m -Name 'color' -Default '') } } elseif ($type -ne 'svg' -and $hasColor) { throw "Add-DrawPackIcon: '$Icon' is a $type image and cannot be recoloured; omit -Color." } $key = "$Pack|$Icon|$useColor" if (-not $script:DrawIconPackCache.ContainsKey($key)) { $file = Join-Path $packDir 'icons' "$Icon.$type" if (-not (Test-Path -LiteralPath $file)) { throw "Add-DrawPackIcon: pack '$Pack' lists '$Icon' but '$file' is missing. Reinstall the pack." } if ($type -eq 'svg') { $svg = Get-Content -LiteralPath $file -Raw if ($useColor) { $svg = Set-DrawSvgColor -Svg $svg -Color $useColor } $bytes = [System.Text.Encoding]::UTF8.GetBytes($svg) $mime = 'image/svg+xml' } else { $bytes = [System.IO.File]::ReadAllBytes($file) $mime = "image/$type" } $b64 = [Convert]::ToBase64String($bytes) $script:DrawIconPackCache[$key] = ConvertTo-DrawImageStyleUri "data:$mime;base64,$b64" } $imageRef = $script:DrawIconPackCache[$key] } $style = 'shape=image;html=1;verticalLabelPosition=bottom;verticalAlign=top;align=center;' + 'labelBackgroundColor=default;imageAspect=1;aspect=fixed;strokeColor=none;' + "image=$imageRef;" $dim = if ($Size -gt 0 -or $Width -gt 0 -or $Height -gt 0) { Get-DrawFitSize -NaturalWidth $natW -NaturalHeight $natH -Size $Size -Width $Width -Height $Height } else { Get-DrawFitSize -NaturalWidth $natW -NaturalHeight $natH -Size 48 } } $cell = Add-DrawShape -Page $Page -Label $Label -Style $style ` -X $X -Y $Y -Width $dim.Width -Height $dim.Height -ParentId $ParentId ` -Metadata $Metadata -Tooltip $Tooltip -PassThru if ($PassThru) { return $cell } } |