main ini
This commit is contained in:
364
launcher/Program.cs
Normal file
364
launcher/Program.cs
Normal file
@@ -0,0 +1,364 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO.Compression;
|
||||
using System.Reflection;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Web.WebView2.Core;
|
||||
using Microsoft.Web.WebView2.WinForms;
|
||||
|
||||
namespace ProjectDashboard;
|
||||
|
||||
static class Program
|
||||
{
|
||||
[STAThread]
|
||||
static void Main()
|
||||
{
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new MainForm());
|
||||
}
|
||||
}
|
||||
|
||||
// One window: makes sure the Node server runs, then shows
|
||||
// http://127.0.0.1:4848 in WebView2. A server that is already running
|
||||
// (second window, start-dashboard.bat) is reused and left alone.
|
||||
//
|
||||
// Two modes:
|
||||
// source - server.js lies next to the exe (Michi's _Tools\ProjectDashboard):
|
||||
// system Node, data in the app's .cache folder.
|
||||
// portable - the exe carries everything as embedded payload.zip (node.exe +
|
||||
// dashboard files) and unpacks it once to %LOCALAPPDATA%\ProjectDashboard\app\<hash>.
|
||||
sealed class MainForm : Form
|
||||
{
|
||||
// DASHBOARD_PORT (also read by server.js) allows a second instance, e.g. for tests
|
||||
static readonly int Port = int.TryParse(Environment.GetEnvironmentVariable("DASHBOARD_PORT"), out var p) ? p : 4848;
|
||||
static readonly string BaseUrl = $"http://127.0.0.1:{Port}/";
|
||||
// DASHBOARD_HOME moves everything (window state, WebView2, unpacked app, data) - used for tests
|
||||
static readonly string DataDir = Environment.GetEnvironmentVariable("DASHBOARD_HOME") is { Length: > 0 } home
|
||||
? Path.GetFullPath(home)
|
||||
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ProjectDashboard");
|
||||
const string WebView2Download = "https://go.microsoft.com/fwlink/p/?LinkId=2124703";
|
||||
|
||||
string appDir = AppContext.BaseDirectory;
|
||||
bool portable;
|
||||
readonly WebView2 web = new() { Dock = DockStyle.Fill, Visible = false };
|
||||
readonly Label status = new()
|
||||
{
|
||||
Dock = DockStyle.Fill,
|
||||
TextAlign = ContentAlignment.MiddleCenter,
|
||||
Font = new Font("Segoe UI", 12f),
|
||||
ForeColor = Color.FromArgb(107, 113, 131),
|
||||
};
|
||||
Process? server; // only set when this window started the server
|
||||
StreamWriter? serverLog;
|
||||
|
||||
public MainForm()
|
||||
{
|
||||
Text = "Projekte";
|
||||
Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
|
||||
MinimumSize = new Size(900, 560);
|
||||
RestoreWindow();
|
||||
FormClosing += (_, e) =>
|
||||
{
|
||||
if (server != null && BackupRunning() &&
|
||||
MessageBox.Show(this, "Das Backup läuft noch.\n\nBeim Schließen wird es abgebrochen (bereits kopierte Dateien bleiben). Trotzdem schließen?",
|
||||
"Projekte", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes)
|
||||
{
|
||||
e.Cancel = true;
|
||||
return;
|
||||
}
|
||||
SaveWindow();
|
||||
};
|
||||
BackColor = Color.FromArgb(245, 246, 250);
|
||||
status.Text = "Starte Dashboard …";
|
||||
Controls.Add(web);
|
||||
Controls.Add(status);
|
||||
Shown += async (_, _) => await StartAsync();
|
||||
FormClosed += (_, _) => StopServer();
|
||||
}
|
||||
|
||||
async Task StartAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(DataDir);
|
||||
if (!await IsServerUp())
|
||||
{
|
||||
string node;
|
||||
if (File.Exists(Path.Combine(appDir, "server.js")))
|
||||
{
|
||||
node = FindNode() ?? throw new Exception("Node.js nicht gefunden. Bitte von nodejs.org installieren.");
|
||||
if (!Directory.Exists(Path.Combine(appDir, "node_modules")))
|
||||
{
|
||||
status.Text = "Installiere einmalig die Abhängigkeiten (npm install) …";
|
||||
await RunHidden("cmd.exe", "/c npm install --no-audit --no-fund", Path.GetDirectoryName(node)!);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
status.Text = "Richte das Dashboard ein …";
|
||||
appDir = await Task.Run(UnpackPayload);
|
||||
portable = true;
|
||||
node = Path.Combine(appDir, "node", "node.exe");
|
||||
}
|
||||
StartServer(node);
|
||||
status.Text = "Starte Server …";
|
||||
var until = DateTime.Now.AddSeconds(25);
|
||||
while (!await IsServerUp())
|
||||
{
|
||||
if (server is { HasExited: true }) throw new Exception($"Server ist abgestürzt. Details:\n{Path.Combine(DataDir, "server.log")}");
|
||||
if (DateTime.Now > until) throw new Exception($"Server antwortet nicht (Port {Port} belegt?).");
|
||||
await Task.Delay(300);
|
||||
}
|
||||
}
|
||||
|
||||
var env = await CoreWebView2Environment.CreateAsync(null, Path.Combine(DataDir, "WebView2"));
|
||||
await web.EnsureCoreWebView2Async(env);
|
||||
var core = web.CoreWebView2;
|
||||
core.Settings.IsStatusBarEnabled = false;
|
||||
core.Settings.AreDevToolsEnabled = true;
|
||||
// Anything outside the dashboard opens in the normal browser.
|
||||
core.NewWindowRequested += (_, e) => { e.Handled = true; OpenExternal(e.Uri); };
|
||||
core.NavigationStarting += (_, e) =>
|
||||
{
|
||||
if (!e.Uri.StartsWith(BaseUrl, StringComparison.OrdinalIgnoreCase)) { e.Cancel = true; OpenExternal(e.Uri); }
|
||||
};
|
||||
core.DocumentTitleChanged += (_, _) => Text = core.DocumentTitle;
|
||||
core.WebMessageReceived += OnWebMessage;
|
||||
if (savedZoom is > 0.3 and < 3) web.ZoomFactor = savedZoom;
|
||||
web.Source = new Uri(BaseUrl);
|
||||
web.Visible = true;
|
||||
status.Visible = false;
|
||||
}
|
||||
catch (WebView2RuntimeNotFoundException)
|
||||
{
|
||||
ShowError("Für das Fenster fehlt die „Microsoft Edge WebView2 Runtime“.\n\nHier klicken, um sie herunterzuladen und zu installieren,\ndanach das Dashboard neu starten.");
|
||||
status.Cursor = Cursors.Hand;
|
||||
status.Click += (_, _) => OpenExternal(WebView2Download);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ShowError("Dashboard konnte nicht starten:\n\n" + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
void ShowError(string text)
|
||||
{
|
||||
status.Text = text;
|
||||
status.ForeColor = Color.FromArgb(220, 38, 38);
|
||||
status.Visible = true;
|
||||
web.Visible = false;
|
||||
}
|
||||
|
||||
// The page asks for a folder dialog ("Durchsuchen…" in the settings):
|
||||
// { type: "pickFolder", id, title, initial } → { type: "folderPicked", id, path }
|
||||
// or for a file dialog (program to start in "Aktionen"):
|
||||
// { type: "pickFile", id, title, initial } → { type: "filePicked", id, path }
|
||||
void OnWebMessage(object? sender, CoreWebView2WebMessageReceivedEventArgs e)
|
||||
{
|
||||
if (!e.Source.StartsWith(BaseUrl, StringComparison.OrdinalIgnoreCase)) return;
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(e.WebMessageAsJson);
|
||||
var m = doc.RootElement;
|
||||
if (m.ValueKind != JsonValueKind.Object) return;
|
||||
var type = m.GetProperty("type").GetString();
|
||||
if (type != "pickFolder" && type != "pickFile") return;
|
||||
var id = m.GetProperty("id").GetString() ?? "";
|
||||
var title = m.TryGetProperty("title", out var t) ? t.GetString() : null;
|
||||
var initial = m.TryGetProperty("initial", out var i) ? i.GetString() : null;
|
||||
if (type == "pickFile")
|
||||
{
|
||||
BeginInvoke(() =>
|
||||
{
|
||||
using var fd = new OpenFileDialog
|
||||
{
|
||||
Title = title ?? "Datei wählen",
|
||||
Filter = "Programme und Seiten (*.exe;*.html;*.htm;*.bat;*.cmd;*.lnk)|*.exe;*.html;*.htm;*.bat;*.cmd;*.lnk|Alle Dateien (*.*)|*.*",
|
||||
CheckFileExists = true,
|
||||
DereferenceLinks = false,
|
||||
};
|
||||
if (!string.IsNullOrWhiteSpace(initial) && Directory.Exists(initial)) fd.InitialDirectory = initial;
|
||||
var file = fd.ShowDialog(this) == DialogResult.OK ? fd.FileName : "";
|
||||
web.CoreWebView2?.PostWebMessageAsJson(JsonSerializer.Serialize(new { type = "filePicked", id, path = file }));
|
||||
});
|
||||
return;
|
||||
}
|
||||
BeginInvoke(() =>
|
||||
{
|
||||
using var dlg = new FolderBrowserDialog
|
||||
{
|
||||
Description = title ?? "Ordner wählen",
|
||||
UseDescriptionForTitle = true,
|
||||
ShowNewFolderButton = true,
|
||||
};
|
||||
if (!string.IsNullOrWhiteSpace(initial) && Directory.Exists(initial)) dlg.InitialDirectory = initial;
|
||||
var path = dlg.ShowDialog(this) == DialogResult.OK ? dlg.SelectedPath : "";
|
||||
web.CoreWebView2?.PostWebMessageAsJson(JsonSerializer.Serialize(new { type = "folderPicked", id, path }));
|
||||
});
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
// Unpacks the embedded payload.zip once per version to <DataDir>\app\<hash>
|
||||
// and removes older versions. Returns the app folder.
|
||||
string UnpackPayload()
|
||||
{
|
||||
var asm = Assembly.GetExecutingAssembly();
|
||||
using var res = asm.GetManifestResourceStream("payload.zip")
|
||||
?? throw new Exception("Diese exe enthält kein Dashboard-Paket (server.js fehlt daneben).");
|
||||
string hash;
|
||||
using (var sha = SHA256.Create()) hash = Convert.ToHexString(sha.ComputeHash(res))[..12].ToLowerInvariant();
|
||||
var appsRoot = Path.Combine(DataDir, "app");
|
||||
var target = Path.Combine(appsRoot, hash);
|
||||
if (File.Exists(Path.Combine(target, ".ok"))) return target;
|
||||
|
||||
Directory.CreateDirectory(appsRoot);
|
||||
var tmp = target + ".tmp";
|
||||
if (Directory.Exists(tmp)) Directory.Delete(tmp, true);
|
||||
res.Position = 0;
|
||||
using (var zip = new ZipArchive(res, ZipArchiveMode.Read)) zip.ExtractToDirectory(tmp);
|
||||
File.WriteAllText(Path.Combine(tmp, ".ok"), DateTime.Now.ToString("s"));
|
||||
if (Directory.Exists(target)) Directory.Delete(target, true);
|
||||
Directory.Move(tmp, target);
|
||||
foreach (var old in Directory.GetDirectories(appsRoot))
|
||||
{
|
||||
if (!string.Equals(old, target, StringComparison.OrdinalIgnoreCase))
|
||||
try { Directory.Delete(old, true); } catch { } // may be in use by another window
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
// Window size/position/zoom are remembered in %LOCALAPPDATA%\ProjectDashboard\window.txt
|
||||
// ("x y w h maximized zoom"). First start: maximized.
|
||||
static readonly string WindowFile = Path.Combine(DataDir, "window.txt");
|
||||
double savedZoom = 1.0;
|
||||
|
||||
void RestoreWindow()
|
||||
{
|
||||
StartPosition = FormStartPosition.CenterScreen;
|
||||
Size = new Size(1500, 950);
|
||||
WindowState = FormWindowState.Maximized;
|
||||
try
|
||||
{
|
||||
var v = File.ReadAllText(WindowFile).Split(' ');
|
||||
var inv = System.Globalization.CultureInfo.InvariantCulture;
|
||||
var rect = new Rectangle(int.Parse(v[0]), int.Parse(v[1]), int.Parse(v[2]), int.Parse(v[3]));
|
||||
savedZoom = double.Parse(v[5], inv);
|
||||
// only restore a position that is still on a connected screen
|
||||
if (Screen.AllScreens.Any(s => s.WorkingArea.IntersectsWith(rect)) && rect.Width >= MinimumSize.Width)
|
||||
{
|
||||
StartPosition = FormStartPosition.Manual;
|
||||
Bounds = rect;
|
||||
}
|
||||
WindowState = v[4] == "1" ? FormWindowState.Maximized : FormWindowState.Normal;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
void SaveWindow()
|
||||
{
|
||||
try
|
||||
{
|
||||
var b = WindowState == FormWindowState.Normal ? Bounds : RestoreBounds;
|
||||
var zoom = web.CoreWebView2 != null ? web.ZoomFactor : savedZoom;
|
||||
Directory.CreateDirectory(DataDir);
|
||||
File.WriteAllText(WindowFile, string.Join(' ', b.X, b.Y, b.Width, b.Height,
|
||||
WindowState == FormWindowState.Maximized ? "1" : "0",
|
||||
zoom.ToString(System.Globalization.CultureInfo.InvariantCulture)));
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
static bool BackupRunning()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(1) };
|
||||
var json = http.GetStringAsync(BaseUrl + "api/backup").GetAwaiter().GetResult();
|
||||
return json.Contains("\"phase\":\"copying\"") || json.Contains("\"phase\":\"checking\"");
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
static async Task<bool> IsServerUp()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(1.5) };
|
||||
var res = await http.GetAsync(BaseUrl + "api/scan");
|
||||
return res.IsSuccessStatusCode;
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
string? FindNode()
|
||||
{
|
||||
foreach (var dir in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(';', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
try
|
||||
{
|
||||
var p = Path.Combine(dir.Trim('"'), "node.exe");
|
||||
if (File.Exists(p)) return p;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
var std = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "nodejs", "node.exe");
|
||||
return File.Exists(std) ? std : null;
|
||||
}
|
||||
|
||||
void StartServer(string node)
|
||||
{
|
||||
serverLog = new StreamWriter(Path.Combine(DataDir, "server.log"), append: false) { AutoFlush = true };
|
||||
var psi = new ProcessStartInfo(node, "server.js")
|
||||
{
|
||||
WorkingDirectory = appDir,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
};
|
||||
// npm/git/code started by the server must be found
|
||||
psi.Environment["PATH"] = Path.GetDirectoryName(node) + ";" + Environment.GetEnvironmentVariable("PATH");
|
||||
// portable: settings, cache and logs live next to the window state, not in the unpacked app
|
||||
if (portable) psi.Environment["DASHBOARD_DATA"] = Path.Combine(DataDir, "data");
|
||||
server = Process.Start(psi) ?? throw new Exception("Node konnte nicht gestartet werden.");
|
||||
server.OutputDataReceived += (_, e) => { if (e.Data != null) lock (serverLog) serverLog.WriteLine(e.Data); };
|
||||
server.ErrorDataReceived += (_, e) => { if (e.Data != null) lock (serverLog) serverLog.WriteLine("ERR " + e.Data); };
|
||||
server.BeginOutputReadLine();
|
||||
server.BeginErrorReadLine();
|
||||
}
|
||||
|
||||
async Task RunHidden(string exe, string args, string extraPath)
|
||||
{
|
||||
var psi = new ProcessStartInfo(exe, args) { WorkingDirectory = appDir, UseShellExecute = false, CreateNoWindow = true };
|
||||
psi.Environment["PATH"] = extraPath + ";" + Environment.GetEnvironmentVariable("PATH");
|
||||
using var p = Process.Start(psi)!;
|
||||
await p.WaitForExitAsync();
|
||||
if (p.ExitCode != 0) throw new Exception("npm install ist fehlgeschlagen.");
|
||||
}
|
||||
|
||||
// Only node itself is stopped: programs it launched (Unity, consoles, ...)
|
||||
// were started detached and keep running.
|
||||
void StopServer()
|
||||
{
|
||||
if (server is { HasExited: false })
|
||||
{
|
||||
// a running backup (robocopy, child of node) is stopped cleanly first
|
||||
try
|
||||
{
|
||||
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(2) };
|
||||
using var req = new HttpRequestMessage(HttpMethod.Post, BaseUrl + "api/backup/cancel");
|
||||
req.Headers.Add("Origin", BaseUrl.TrimEnd('/'));
|
||||
http.Send(req);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
try { if (server is { HasExited: false }) server.Kill(entireProcessTree: false); } catch { }
|
||||
serverLog?.Dispose();
|
||||
}
|
||||
|
||||
static void OpenExternal(string uri)
|
||||
{
|
||||
try { Process.Start(new ProcessStartInfo(uri) { UseShellExecute = true }); } catch { }
|
||||
}
|
||||
}
|
||||
42
launcher/ProjectDashboard.csproj
Normal file
42
launcher/ProjectDashboard.csproj
Normal file
@@ -0,0 +1,42 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!-- Desktop window for the project dashboard: starts server.js (Node) hidden
|
||||
and shows the UI in a WebView2 window. Build with ..\build.ps1. -->
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net8.0-windows</TargetFramework>
|
||||
<UseWindowsForms>true</UseWindowsForms>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<AssemblyName>ProjectDashboard</AssemblyName>
|
||||
<RootNamespace>ProjectDashboard</RootNamespace>
|
||||
<ApplicationIcon>app.ico</ApplicationIcon>
|
||||
<ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
|
||||
<Product>Projekt-Dashboard</Product>
|
||||
<Version>1.0.0</Version>
|
||||
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
||||
<SelfContained>false</SelfContained>
|
||||
<PublishSingleFile>true</PublishSingleFile>
|
||||
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
|
||||
<DebugType>none</DebugType>
|
||||
<SatelliteResourceLanguages>de</SatelliteResourceLanguages>
|
||||
<!-- WebView2 also ships a WPF control; its WindowsBase reference clashes harmlessly with WinForms -->
|
||||
<NoWarn>$(NoWarn);MSB3277</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- Portable build (build.ps1 -Release): one exe for other PCs - .NET runtime
|
||||
included, and the whole dashboard incl. node.exe embedded as payload.zip. -->
|
||||
<PropertyGroup Condition="'$(Portable)' == 'true'">
|
||||
<SelfContained>true</SelfContained>
|
||||
<EnableCompressionInSingleFile>true</EnableCompressionInSingleFile>
|
||||
<InvariantGlobalization>false</InvariantGlobalization>
|
||||
</PropertyGroup>
|
||||
<ItemGroup Condition="'$(Portable)' == 'true'">
|
||||
<EmbeddedResource Include="payload.zip" LogicalName="payload.zip" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2903.40" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
BIN
launcher/app.ico
Normal file
BIN
launcher/app.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 23 KiB |
BIN
launcher/app.png
Normal file
BIN
launcher/app.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
63
launcher/make-icon.ps1
Normal file
63
launcher/make-icon.ps1
Normal file
@@ -0,0 +1,63 @@
|
||||
# Draws the app icon (indigo/violet rounded square with a white "layers" glyph,
|
||||
# same look as the dashboard logo) and writes launcher\app.ico with 16-256 px.
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$out = Join-Path $PSScriptRoot 'app.ico'
|
||||
|
||||
function New-IconPng([int]$size) {
|
||||
$bmp = New-Object System.Drawing.Bitmap $size, $size
|
||||
$g = [System.Drawing.Graphics]::FromImage($bmp)
|
||||
$g.SmoothingMode = 'AntiAlias'
|
||||
$g.Clear([System.Drawing.Color]::Transparent)
|
||||
|
||||
# rounded square with diagonal gradient
|
||||
$r = [single]($size * 0.22)
|
||||
$rect = New-Object System.Drawing.RectangleF 0, 0, $size, $size
|
||||
$path = New-Object System.Drawing.Drawing2D.GraphicsPath
|
||||
$d = $r * 2
|
||||
$path.AddArc(0, 0, $d, $d, 180, 90)
|
||||
$path.AddArc($size - $d, 0, $d, $d, 270, 90)
|
||||
$path.AddArc($size - $d, $size - $d, $d, $d, 0, 90)
|
||||
$path.AddArc(0, $size - $d, $d, $d, 90, 90)
|
||||
$path.CloseFigure()
|
||||
$brush = New-Object System.Drawing.Drawing2D.LinearGradientBrush $rect, ([System.Drawing.Color]::FromArgb(99, 102, 241)), ([System.Drawing.Color]::FromArgb(139, 92, 246)), 45
|
||||
$g.FillPath($brush, $path)
|
||||
|
||||
# layers glyph: a diamond on top, two chevrons below (Lucide "layers" shape)
|
||||
$s = $size / 24.0
|
||||
$pen = New-Object System.Drawing.Pen ([System.Drawing.Color]::White), ([single][Math]::Max(1.2, 1.9 * $s))
|
||||
$pen.LineJoin = 'Round'; $pen.StartCap = 'Round'; $pen.EndCap = 'Round'
|
||||
$ox = 0; $oy = 0.6 * $s
|
||||
function P($x, $y) { New-Object System.Drawing.PointF ([single]($x * $s + $ox)), ([single]($y * $s + $oy)) }
|
||||
$g.DrawPolygon($pen, [System.Drawing.PointF[]]@((P 12 4.2), (P 19.5 7.6), (P 12 11), (P 4.5 7.6)))
|
||||
$g.DrawLines($pen, [System.Drawing.PointF[]]@((P 4.5 11.8), (P 12 15.2), (P 19.5 11.8)))
|
||||
$g.DrawLines($pen, [System.Drawing.PointF[]]@((P 4.5 15.8), (P 12 19.2), (P 19.5 15.8)))
|
||||
|
||||
$g.Dispose()
|
||||
$ms = New-Object System.IO.MemoryStream
|
||||
$bmp.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)
|
||||
$bmp.Dispose()
|
||||
return , $ms.ToArray()
|
||||
}
|
||||
|
||||
# ICO container with PNG-compressed entries
|
||||
$sizes = 16, 24, 32, 48, 64, 128, 256
|
||||
$images = foreach ($sz in $sizes) { , (New-IconPng $sz) }
|
||||
$fs = [System.IO.File]::Create($out)
|
||||
$w = New-Object System.IO.BinaryWriter $fs
|
||||
$w.Write([uint16]0); $w.Write([uint16]1); $w.Write([uint16]$sizes.Count)
|
||||
$offset = 6 + 16 * $sizes.Count
|
||||
for ($i = 0; $i -lt $sizes.Count; $i++) {
|
||||
$sz = $sizes[$i]; $data = $images[$i]
|
||||
$w.Write([byte]($(if ($sz -ge 256) { 0 } else { $sz })))
|
||||
$w.Write([byte]($(if ($sz -ge 256) { 0 } else { $sz })))
|
||||
$w.Write([byte]0); $w.Write([byte]0)
|
||||
$w.Write([uint16]1); $w.Write([uint16]32)
|
||||
$w.Write([uint32]$data.Length); $w.Write([uint32]$offset)
|
||||
$offset += $data.Length
|
||||
}
|
||||
foreach ($data in $images) { $w.Write($data) }
|
||||
$w.Close()
|
||||
# also a PNG preview for the dashboard / README
|
||||
[System.IO.File]::WriteAllBytes((Join-Path $PSScriptRoot 'app.png'), (New-IconPng 256))
|
||||
Write-Host "icon -> $out"
|
||||
Reference in New Issue
Block a user