This commit is contained in:
AlexGyver committed 2026-06-24 22:49:13 +03:00
1 parent d5365043d1
commit 4ec1a8b8df
61 files changed
+3065 -296

No files matched your search

+5 -5
View File
@@ -1,4 +1,4 @@
name: Build ArdulibsManager Release
name: Build ArduManager Release
on:
push:
@@ -38,11 +38,11 @@ jobs:
dotnet-version: "8.0.x"
- name: Restore
run: dotnet restore ./src/ArdulibsManager.App/ArdulibsManager.App.csproj
run: dotnet restore ./src/ArduManager.App/ArduManager.App.csproj
- name: Publish ${{ matrix.arch }}
run: |
dotnet publish ./src/ArdulibsManager.App/ArdulibsManager.App.csproj `
dotnet publish ./src/ArduManager.App/ArduManager.App.csproj `
-c Release `
-r ${{ matrix.rid }} `
--self-contained true `
@@ -64,10 +64,10 @@ jobs:
Move-Item `
-Path $exe.FullName `
-Destination ./ArdulibsManager-${{ matrix.arch }}.exe `
-Destination ./ArduManager-${{ matrix.arch }}.exe `
-Force
- name: Upload EXE to GitHub Release
uses: softprops/action-gh-release@v2
with:
files: ./ArdulibsManager-${{ matrix.arch }}.exe
files: ./ArduManager-${{ matrix.arch }}.exe
+1 -1
View File
@@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArdulibsManager.App", "src\ArdulibsManager.App\ArdulibsManager.App.csproj", "{F268DE91-7C75-4B18-99D8-7FB7F5156CD8}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArduManager.App", "src\ArduManager.App\ArduManager.App.csproj", "{F268DE91-7C75-4B18-99D8-7FB7F5156CD8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
+6 -5
View File
@@ -1,15 +1,16 @@
# ArdulibsManager
Кастомный менеджер Arduino-библиотек для Windows. Работает напрямую с GitHub, а не с экосистемой Arduino, которая заблокировала доступ пользователям из России
# ArduManager
Кастомный менеджер Arduino-библиотек и платформ для Windows. Работает напрямую с GitHub, а не с экосистемой Arduino, которая заблокировала доступ пользователям из России
Скачать свежую версию:
- [Windows 64 bit](https://github.com/AlexGyver/ArdulibsManager/releases/latest/download/ArdulibsManager-x64.exe)
- [Windows 32 bit](https://github.com/AlexGyver/ArdulibsManager/releases/latest/download/ArdulibsManager-x86.exe)
- [Windows 64 bit](https://github.com/AlexGyver/ArduManager/releases/latest/download/ArduManager-x64.exe)
- [Windows 32 bit](https://github.com/AlexGyver/ArduManager/releases/latest/download/ArduManager-x86.exe)
Возможности:
- Работа напрямую с GitHub-списком библиотек в обход Arduino
- Рекурсивная установка зависимостей
- Сканирование и менеджмент установленных библиотек
- Проверка обновлений
- Установка и обновление платформ
## GitHub token
Токен необязателен. Он нужен только для повышения лимитов GitHub API. Когда может понадобиться:
@@ -40,4 +41,4 @@
- Если dependency name сильно отличается от repo name, автоматический поиск зависимости может не сработать
## Запуск исходника
Нужен [SDK .NET 8](https://dotnet.microsoft.com/ru-ru/download/dotnet/8.0). Далее запускаем `dotnet restore && dotnet run --project src/ArdulibsManager.App` или `run.bat` из репозитория.
Нужен [SDK .NET 8](https://dotnet.microsoft.com/ru-ru/download/dotnet/8.0). Далее запускаем `dotnet restore && dotnet run --project src/ArduManager.App` или `run.bat` из репозитория.
+2
View File
@@ -0,0 +1,2 @@
@echo off
start "" "%APPDATA%\ArduManager\boards\logs"
+3 -2
View File
@@ -1,6 +1,7 @@
@echo off
chcp 65001 >nul
dotnet restore
if errorlevel 1 exit /b %errorlevel%
dotnet run --project src/ArdulibsManager.App
if errorlevel 1 exit /b %errorlevel%
dotnet run --project src/ArduManager.App
if errorlevel 1 exit /b %errorlevel%
@@ -1,7 +1,8 @@
<Application x:Class="ArdulibsManager.App"
<Application x:Class="ArduManager.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVisibility" />
<SolidColorBrush x:Key="AccentBrush" Color="#2D7D46" />
<SolidColorBrush x:Key="MutedBrush" Color="#666666" />
<Style TargetType="Button">
@@ -1,8 +1,9 @@
using System.Text;
using System.Windows;
using ArdulibsManager.Views;
using ArduManager.Views;
using ArduboardsManager.App.Services;
namespace ArdulibsManager;
namespace ArduManager;
public partial class App : Application
{
@@ -12,6 +13,16 @@ public partial class App : Application
{
base.OnStartup(e);
try
{
LogService.Info("Application startup");
new StartupCleanupService(new ArduinoPathService()).CleanupLeftovers();
}
catch
{
// Cleanup/logging must not prevent the main app from starting.
}
var window = new MainWindow();
MainWindow = window;
window.Show();
@@ -21,7 +32,7 @@ public partial class App : Application
WriteStartupError(ex);
MessageBox.Show(
"Приложение не смогло запуститься. Подробности записаны в startup-error.log рядом с приложением." + Environment.NewLine + Environment.NewLine + ex.Message,
"ArdulibsManager",
"ArduManager",
MessageBoxButton.OK,
MessageBoxImage.Error);
Shutdown(1);
@@ -5,9 +5,16 @@
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UseWPF>true</UseWPF>
<LangVersion>latest</LangVersion>
<EnableWindowsTargeting>true</EnableWindowsTargeting>
<ApplicationIcon>Assets\app.ico</ApplicationIcon>
<AssemblyName>ArdulibsManager</AssemblyName>
<RootNamespace>ArdulibsManager</RootNamespace>
<AssemblyName>ArduManager</AssemblyName>
<RootNamespace>ArduManager</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Content Include="standard-platforms.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>
File renamed without changes.
@@ -0,0 +1,3 @@
namespace ArduboardsManager.App.Models;
public sealed record InstallProgress(string Message, double Percent);
@@ -0,0 +1,7 @@
namespace ArduboardsManager.App.Models;
public sealed class PackageIndexDocument
{
public required string SourceUrl { get; init; }
public required PackageIndex Index { get; init; }
}
@@ -0,0 +1,136 @@
using System.Text.Json.Serialization;
namespace ArduboardsManager.App.Models;
public sealed class FlexibleNullableStringConverter : JsonConverter<string?>
{
public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return reader.TokenType switch
{
JsonTokenType.String => reader.GetString(),
JsonTokenType.Number => reader.TryGetInt64(out var longValue)
? longValue.ToString(CultureInfo.InvariantCulture)
: reader.GetDouble().ToString(CultureInfo.InvariantCulture),
JsonTokenType.True => "true",
JsonTokenType.False => "false",
JsonTokenType.Null => null,
_ => JsonDocument.ParseValue(ref reader).RootElement.GetRawText()
};
}
public override void Write(Utf8JsonWriter writer, string? value, JsonSerializerOptions options)
{
if (value is null)
writer.WriteNullValue();
else
writer.WriteStringValue(value);
}
}
public sealed class PackageIndex
{
[JsonPropertyName("packages")]
public List<ArduinoPackage> Packages { get; set; } = new();
}
public sealed class ArduinoPackage
{
[JsonPropertyName("name")]
public string Name { get; set; } = string.Empty;
[JsonPropertyName("maintainer")]
public string? Maintainer { get; set; }
[JsonPropertyName("websiteURL")]
public string? WebsiteUrl { get; set; }
[JsonPropertyName("platforms")]
public List<ArduinoPlatform> Platforms { get; set; } = new();
[JsonPropertyName("tools")]
public List<ArduinoTool> Tools { get; set; } = new();
}
public sealed class ArduinoPlatform
{
[JsonPropertyName("name")]
public string Name { get; set; } = string.Empty;
[JsonPropertyName("architecture")]
public string Architecture { get; set; } = string.Empty;
[JsonPropertyName("version")]
public string Version { get; set; } = string.Empty;
[JsonPropertyName("category")]
public string? Category { get; set; }
[JsonPropertyName("url")]
public string Url { get; set; } = string.Empty;
[JsonPropertyName("archiveFileName")]
public string ArchiveFileName { get; set; } = string.Empty;
[JsonPropertyName("checksum")]
public string? Checksum { get; set; }
[JsonPropertyName("size")]
[JsonConverter(typeof(FlexibleNullableStringConverter))]
public string? Size { get; set; }
[JsonPropertyName("boards")]
public List<ArduinoBoard> Boards { get; set; } = new();
[JsonPropertyName("toolsDependencies")]
public List<ToolDependency> ToolsDependencies { get; set; } = new();
}
public sealed class ArduinoBoard
{
[JsonPropertyName("name")]
public string Name { get; set; } = string.Empty;
}
public sealed class ToolDependency
{
[JsonPropertyName("packager")]
public string Packager { get; set; } = string.Empty;
[JsonPropertyName("name")]
public string Name { get; set; } = string.Empty;
[JsonPropertyName("version")]
public string Version { get; set; } = string.Empty;
}
public sealed class ArduinoTool
{
[JsonPropertyName("name")]
public string Name { get; set; } = string.Empty;
[JsonPropertyName("version")]
public string Version { get; set; } = string.Empty;
[JsonPropertyName("systems")]
public List<ToolSystem> Systems { get; set; } = new();
}
public sealed class ToolSystem
{
[JsonPropertyName("host")]
public string Host { get; set; } = string.Empty;
[JsonPropertyName("url")]
public string Url { get; set; } = string.Empty;
[JsonPropertyName("archiveFileName")]
public string ArchiveFileName { get; set; } = string.Empty;
[JsonPropertyName("checksum")]
public string? Checksum { get; set; }
[JsonPropertyName("size")]
[JsonConverter(typeof(FlexibleNullableStringConverter))]
public string? Size { get; set; }
}
@@ -0,0 +1,15 @@
namespace ArduboardsManager.App.Models;
public sealed class PlatformDescriptor
{
public required string SourceUrl { get; init; }
public required string PackageName { get; init; }
public required string Architecture { get; init; }
public required string DisplayName { get; init; }
public string? GitHubUrl { get; init; }
public required IReadOnlyDictionary<string, ArduinoPlatform> PlatformsByVersion { get; init; }
public string Key => $"{PackageName}:{Architecture}";
public ArduinoPlatform GetPlatform(string version) => PlatformsByVersion[version];
}
@@ -0,0 +1,6 @@
namespace ArduboardsManager.App.Models;
public sealed class SettingsData
{
public List<string> PackageUrls { get; set; } = new();
}
@@ -0,0 +1,7 @@
namespace ArduboardsManager.App.Models;
public sealed class StandardPlatformLink
{
public string Name { get; set; } = string.Empty;
public string Url { get; set; } = string.Empty;
}
@@ -0,0 +1,24 @@
namespace ArduboardsManager.App.Services;
public static class AppPaths
{
public static string AppDataDirectory { get; } = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"ArduManager",
"boards");
public static string LocalAppDataDirectory { get; } = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"ArduManager",
"boards");
public static string SettingsFile { get; } = Path.Combine(AppDataDirectory, "settings.json");
public static string CacheDirectory { get; } = Path.Combine(LocalAppDataDirectory, "cache");
public static string LogsDirectory { get; } = Path.Combine(AppDataDirectory, "logs");
public static string CurrentLogFile { get; } = Path.Combine(LogsDirectory, "app.log");
public static string LastRunLogFile { get; } = Path.Combine(LogsDirectory, "last-run.log");
}
@@ -0,0 +1,81 @@
using System.Diagnostics;
using System.IO.Compression;
namespace ArduboardsManager.App.Services;
public sealed class ArchiveExtractor
{
public async Task ExtractAsync(string archiveFile, string destinationDirectory, CancellationToken cancellationToken = default)
{
Directory.CreateDirectory(destinationDirectory);
var extension = Path.GetExtension(archiveFile).ToLowerInvariant();
if (extension == ".zip")
{
ZipFile.ExtractToDirectory(archiveFile, destinationDirectory, overwriteFiles: true);
return;
}
await ExtractWithWindowsTarAsync(archiveFile, destinationDirectory, cancellationToken);
}
private static async Task ExtractWithWindowsTarAsync(string archiveFile, string destinationDirectory, CancellationToken cancellationToken)
{
var psi = new ProcessStartInfo
{
FileName = "tar",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
psi.ArgumentList.Add("-xf");
psi.ArgumentList.Add(archiveFile);
psi.ArgumentList.Add("-C");
psi.ArgumentList.Add(destinationDirectory);
using var process = Process.Start(psi)
?? throw new InvalidOperationException("Не удалось запустить tar.exe для распаковки архива.");
var stdoutTask = process.StandardOutput.ReadToEndAsync(cancellationToken);
var stderrTask = process.StandardError.ReadToEndAsync(cancellationToken);
await process.WaitForExitAsync(cancellationToken);
var stdout = await stdoutTask;
var stderr = await stderrTask;
if (process.ExitCode != 0)
{
var details = string.IsNullOrWhiteSpace(stderr) ? stdout : stderr;
throw new InvalidOperationException($"tar.exe не смог распаковать архив '{archiveFile}'. Код: {process.ExitCode}. {details}");
}
}
public static string FindContentRoot(string extractedDirectory, bool platformArchive)
{
if (platformArchive)
{
var platformFile = Directory.EnumerateFiles(extractedDirectory, "platform.txt", SearchOption.AllDirectories)
.OrderBy(x => x.Length)
.FirstOrDefault();
if (!string.IsNullOrWhiteSpace(platformFile))
return Path.GetDirectoryName(platformFile)!;
var boardsFile = Directory.EnumerateFiles(extractedDirectory, "boards.txt", SearchOption.AllDirectories)
.OrderBy(x => x.Length)
.FirstOrDefault();
if (!string.IsNullOrWhiteSpace(boardsFile))
return Path.GetDirectoryName(boardsFile)!;
}
var topDirectories = Directory.EnumerateDirectories(extractedDirectory).ToList();
var topFiles = Directory.EnumerateFiles(extractedDirectory).ToList();
return topDirectories.Count == 1 && topFiles.Count == 0
? topDirectories[0]
: extractedDirectory;
}
}
@@ -0,0 +1,103 @@
namespace ArduboardsManager.App.Services;
public sealed class ArduinoPathService
{
public string DataDirectory { get; }
public ArduinoPathService()
{
var overrideDir = Environment.GetEnvironmentVariable("ARDUINO_DATA_DIR");
DataDirectory = !string.IsNullOrWhiteSpace(overrideDir)
? overrideDir
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Arduino15");
}
public string GetPackageDirectory(string packager)
{
return Path.Combine(DataDirectory, "packages", packager);
}
public string GetPackageHardwareDirectory(string packager)
{
return Path.Combine(GetPackageDirectory(packager), "hardware");
}
public string GetPackageToolsDirectory(string packager)
{
return Path.Combine(GetPackageDirectory(packager), "tools");
}
public string GetPlatformVersionsDirectory(string packager, string architecture)
{
return Path.Combine(GetPackageHardwareDirectory(packager), architecture);
}
public string GetPlatformVersionDirectory(string packager, string architecture, string version)
{
return Path.Combine(GetPlatformVersionsDirectory(packager, architecture), version);
}
public string GetToolFamilyDirectory(string packager, string toolName)
{
return Path.Combine(GetPackageToolsDirectory(packager), toolName);
}
public string GetToolVersionDirectory(string packager, string toolName, string version)
{
return Path.Combine(GetToolFamilyDirectory(packager, toolName), version);
}
public bool HasAnyPlatformFiles(string packager, string architecture)
{
var dir = GetPlatformVersionsDirectory(packager, architecture);
return Directory.Exists(dir) && Directory.EnumerateFileSystemEntries(dir).Any();
}
public bool HasAnyLocalFilesForDescriptor(Models.PlatformDescriptor descriptor)
{
if (HasAnyPlatformFiles(descriptor.PackageName, descriptor.Architecture))
return true;
foreach (var dependency in GetToolDependencies(descriptor))
{
var dir = GetToolVersionDirectory(dependency.Packager, dependency.Name, dependency.Version);
if (Directory.Exists(dir))
return true;
}
var packageDir = GetPackageDirectory(descriptor.PackageName);
return Directory.Exists(packageDir) && Directory.EnumerateFileSystemEntries(packageDir).Any();
}
public static IReadOnlyList<Models.ToolDependency> GetToolDependencies(Models.PlatformDescriptor descriptor)
{
return descriptor.PlatformsByVersion.Values
.SelectMany(platform => platform.ToolsDependencies ?? new List<Models.ToolDependency>())
.Where(x => !string.IsNullOrWhiteSpace(x.Packager)
&& !string.IsNullOrWhiteSpace(x.Name)
&& !string.IsNullOrWhiteSpace(x.Version))
.GroupBy(x => $"{x.Packager}\0{x.Name}\0{x.Version}", StringComparer.OrdinalIgnoreCase)
.Select(x => x.First())
.ToList();
}
public IReadOnlyList<string> GetInstalledPlatformVersions(string packager, string architecture)
{
var dir = GetPlatformVersionsDirectory(packager, architecture);
if (!Directory.Exists(dir))
return Array.Empty<string>();
return Directory.EnumerateDirectories(dir)
.Select(Path.GetFileName)
.Where(x => !string.IsNullOrWhiteSpace(x))
.Cast<string>()
.Where(x => !x.Contains(".installing-", StringComparison.OrdinalIgnoreCase))
.OrderByDescending(x => x, VersionTextComparer.Instance)
.ToList();
}
public string? GetInstalledPlatformVersion(string packager, string architecture)
{
return GetInstalledPlatformVersions(packager, architecture).FirstOrDefault();
}
}
@@ -0,0 +1,54 @@
using System.Runtime.InteropServices;
using ArduboardsManager.App.Models;
namespace ArduboardsManager.App.Services;
public static class HostMatcher
{
public static ToolSystem SelectBestSystem(IReadOnlyList<ToolSystem> systems)
{
if (systems.Count == 0)
throw new InvalidOperationException("У tool нет systems[].");
var hosts = GetPreferredHostFragments();
foreach (var host in hosts)
{
var match = systems.FirstOrDefault(x => x.Host.Contains(host, StringComparison.OrdinalIgnoreCase));
if (match is not null)
return match;
}
var fallback = systems.FirstOrDefault(x => x.Host.Contains("mingw", StringComparison.OrdinalIgnoreCase))
?? systems.FirstOrDefault(x => x.Host.Contains("windows", StringComparison.OrdinalIgnoreCase));
return fallback ?? throw new InvalidOperationException(
$"Не нашёл подходящий tool archive для этой ОС. Доступные host: {string.Join(", ", systems.Select(x => x.Host))}");
}
private static IReadOnlyList<string> GetPreferredHostFragments()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return RuntimeInformation.OSArchitecture is Architecture.X64 or Architecture.Arm64
? new[] { "x86_64-mingw32", "amd64-mingw32", "i686-mingw32", "mingw32" }
: new[] { "i686-mingw32", "x86_64-mingw32", "mingw32" };
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return RuntimeInformation.OSArchitecture is Architecture.Arm64
? new[] { "arm64-apple-darwin", "aarch64-apple-darwin", "x86_64-apple-darwin", "apple-darwin" }
: new[] { "x86_64-apple-darwin", "i386-apple-darwin", "apple-darwin" };
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
return RuntimeInformation.OSArchitecture is Architecture.Arm64
? new[] { "aarch64-linux-gnu", "arm64-linux-gnu", "x86_64-pc-linux-gnu", "linux-gnu" }
: new[] { "x86_64-pc-linux-gnu", "i686-pc-linux-gnu", "linux-gnu" };
}
return Array.Empty<string>();
}
}
@@ -0,0 +1,40 @@
using System.Text;
namespace ArduboardsManager.App.Services;
public static class LogService
{
private static readonly object Sync = new();
public static void Info(string message) => Write("INFO", message, null);
public static void Error(string message, Exception? exception = null) => Write("ERROR", message, exception);
private static void Write(string level, string message, Exception? exception)
{
try
{
Directory.CreateDirectory(AppPaths.LogsDirectory);
var builder = new StringBuilder();
builder.Append('[')
.Append(DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff zzz"))
.Append("] ")
.Append(level)
.Append(" ")
.AppendLine(message);
if (exception is not null)
builder.AppendLine(exception.ToString());
lock (Sync)
{
File.AppendAllText(AppPaths.CurrentLogFile, builder.ToString(), Encoding.UTF8);
}
}
catch
{
// Logging must never crash the application.
}
}
}
@@ -0,0 +1,99 @@
using System.Net.Http;
using System.Text.Json;
using ArduboardsManager.App.Models;
namespace ArduboardsManager.App.Services;
public sealed class PackageIndexService
{
private static readonly TimeSpan ResponseHeaderTimeout = TimeSpan.FromSeconds(45);
private static readonly TimeSpan DownloadIdleTimeout = TimeSpan.FromSeconds(30);
private readonly HttpClient _httpClient = new()
{
Timeout = System.Threading.Timeout.InfiniteTimeSpan
};
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNameCaseInsensitive = true,
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true
};
public async Task<PackageIndexDocument> DownloadAsync(string url, CancellationToken cancellationToken = default)
{
LogService.Info($"Downloading package index: {url}");
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || uri.Scheme is not ("http" or "https"))
throw new InvalidOperationException("Нужна корректная http/https-ссылка на package index JSON.");
using var response = await GetResponseWithTimeoutAsync(uri, cancellationToken);
response.EnsureSuccessStatusCode();
var bytes = await ReadResponseWithIdleTimeoutAsync(response, uri.ToString(), cancellationToken);
var index = JsonSerializer.Deserialize<PackageIndex>(bytes, JsonOptions);
if (index?.Packages is null || index.Packages.Count == 0)
throw new InvalidOperationException("JSON скачан, но в нём не найдены packages[].");
LogService.Info($"Package index loaded: {url}. Packages: {index.Packages.Count}");
return new PackageIndexDocument
{
SourceUrl = url,
Index = index
};
}
private async Task<HttpResponseMessage> GetResponseWithTimeoutAsync(Uri uri, CancellationToken cancellationToken)
{
using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeoutCts.CancelAfter(ResponseHeaderTimeout);
try
{
return await _httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, timeoutCts.Token);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
throw new TimeoutException($"Сервер не ответил за {FormatTimeout(ResponseHeaderTimeout)}: {uri}");
}
}
private static async Task<byte[]> ReadResponseWithIdleTimeoutAsync(HttpResponseMessage response, string url, CancellationToken cancellationToken)
{
var buffer = new byte[1024 * 64];
await using var input = await response.Content.ReadAsStreamAsync(cancellationToken);
await using var output = new MemoryStream();
while (true)
{
var readTask = input.ReadAsync(buffer.AsMemory(0, buffer.Length), cancellationToken).AsTask();
var timeoutTask = Task.Delay(DownloadIdleTimeout, cancellationToken);
var completed = await Task.WhenAny(readTask, timeoutTask);
if (completed != readTask)
{
if (cancellationToken.IsCancellationRequested)
cancellationToken.ThrowIfCancellationRequested();
throw new TimeoutException($"Загрузка index JSON остановилась: за {FormatTimeout(DownloadIdleTimeout)} не получено новых данных. URL: {url}");
}
var read = await readTask;
if (read == 0)
break;
await output.WriteAsync(buffer.AsMemory(0, read), cancellationToken);
}
return output.ToArray();
}
private static string FormatTimeout(TimeSpan value)
{
return value.TotalSeconds >= 60
? $"{value.TotalMinutes:0.#} мин"
: $"{value.TotalSeconds:0} сек";
}
}
@@ -0,0 +1,509 @@
using System.Globalization;
using System.Net.Http;
using System.Security.Cryptography;
using ArduboardsManager.App.Models;
namespace ArduboardsManager.App.Services;
public sealed class PackageInstaller
{
private readonly ArduinoPathService _paths;
private readonly ArchiveExtractor _extractor = new();
private static readonly TimeSpan ResponseHeaderTimeout = TimeSpan.FromSeconds(45);
private static readonly TimeSpan DownloadIdleTimeout = TimeSpan.FromSeconds(30);
private readonly HttpClient _httpClient = new()
{
Timeout = System.Threading.Timeout.InfiniteTimeSpan
};
public PackageInstaller(ArduinoPathService paths)
{
_paths = paths;
}
public async Task InstallAsync(
PlatformDescriptor descriptor,
string version,
IReadOnlyList<PackageIndexDocument> knownIndexes,
IProgress<InstallProgress> progress,
CancellationToken cancellationToken = default)
{
LogService.Info($"Install requested: {descriptor.Key}@{version}");
var platform = descriptor.GetPlatform(version);
var dependencies = platform.ToolsDependencies ?? new List<ToolDependency>();
var totalSteps = dependencies.Count + 1;
var step = 0;
foreach (var dependency in dependencies)
{
cancellationToken.ThrowIfCancellationRequested();
await InstallToolDependencyAsync(dependency, knownIndexes, step, totalSteps, progress, cancellationToken);
step++;
}
await InstallPlatformArchiveAsync(descriptor, platform, step, totalSteps, progress, cancellationToken);
LogService.Info($"Install completed: {descriptor.Key}@{version}");
progress.Report(new InstallProgress("Готово", 100));
}
public Task DeletePlatformAsync(
PlatformDescriptor descriptor,
IReadOnlyList<PackageIndexDocument> knownIndexes,
CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
LogService.Info($"Delete platform requested: {descriptor.Key}");
var platformDir = _paths.GetPlatformVersionsDirectory(descriptor.PackageName, descriptor.Architecture);
DeleteDirectoryForce(platformDir, cancellationToken);
DeleteEmptyAncestors(platformDir, _paths.GetPackageDirectory(descriptor.PackageName), cancellationToken);
foreach (var dependency in ArduinoPathService.GetToolDependencies(descriptor))
{
cancellationToken.ThrowIfCancellationRequested();
if (IsToolDependencyUsedByOtherInstalledPlatform(dependency, descriptor, knownIndexes))
{
LogService.Info($"Tool kept because another installed platform uses it: {dependency.Packager}:{dependency.Name}@{dependency.Version}");
continue;
}
var toolVersionDir = _paths.GetToolVersionDirectory(dependency.Packager, dependency.Name, dependency.Version);
DeleteDirectoryForce(toolVersionDir, cancellationToken);
DeleteEmptyAncestors(toolVersionDir, _paths.GetPackageDirectory(dependency.Packager), cancellationToken);
}
DeleteEmptyDirectory(_paths.GetPackageHardwareDirectory(descriptor.PackageName), cancellationToken);
DeleteEmptyDirectory(_paths.GetPackageToolsDirectory(descriptor.PackageName), cancellationToken);
DeleteEmptyDirectory(_paths.GetPackageDirectory(descriptor.PackageName), cancellationToken);
return Task.CompletedTask;
}
private bool IsToolDependencyUsedByOtherInstalledPlatform(
ToolDependency dependency,
PlatformDescriptor deletingDescriptor,
IReadOnlyList<PackageIndexDocument> knownIndexes)
{
foreach (var entry in knownIndexes
.SelectMany(document => document.Index.Packages.SelectMany(package => package.Platforms.Select(platform => new
{
Package = package,
Platform = platform
}))))
{
if (string.Equals(entry.Package.Name, deletingDescriptor.PackageName, StringComparison.OrdinalIgnoreCase) &&
string.Equals(entry.Platform.Architecture, deletingDescriptor.Architecture, StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (!_paths.GetInstalledPlatformVersions(entry.Package.Name, entry.Platform.Architecture).Any())
continue;
var isUsed = (entry.Platform.ToolsDependencies ?? new List<ToolDependency>()).Any(x =>
string.Equals(x.Packager, dependency.Packager, StringComparison.OrdinalIgnoreCase) &&
string.Equals(x.Name, dependency.Name, StringComparison.OrdinalIgnoreCase) &&
string.Equals(x.Version, dependency.Version, StringComparison.OrdinalIgnoreCase));
if (isUsed)
return true;
}
return false;
}
private static void DeleteEmptyAncestors(string startDirectory, string stopDirectory, CancellationToken cancellationToken)
{
var current = Directory.GetParent(startDirectory)?.FullName;
var stop = Path.GetFullPath(stopDirectory).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
while (!string.IsNullOrWhiteSpace(current))
{
cancellationToken.ThrowIfCancellationRequested();
var normalized = Path.GetFullPath(current).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
if (!normalized.StartsWith(stop, StringComparison.OrdinalIgnoreCase))
break;
DeleteEmptyDirectory(normalized, cancellationToken);
if (string.Equals(normalized, stop, StringComparison.OrdinalIgnoreCase))
break;
current = Directory.GetParent(normalized)?.FullName;
}
}
private static void DeleteEmptyDirectory(string directory, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (!Directory.Exists(directory))
return;
if (Directory.EnumerateFileSystemEntries(directory).Any())
return;
try
{
File.SetAttributes(directory, FileAttributes.Normal);
}
catch
{
// Best effort.
}
Directory.Delete(directory, recursive: false);
}
private static void DeleteDirectoryForce(string directory, CancellationToken cancellationToken)
{
if (!Directory.Exists(directory))
return;
foreach (var file in Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories))
{
cancellationToken.ThrowIfCancellationRequested();
try
{
File.SetAttributes(file, FileAttributes.Normal);
}
catch
{
// Best effort: Directory.Delete will report the actual deletion error if it still fails.
}
}
foreach (var subDirectory in Directory.EnumerateDirectories(directory, "*", SearchOption.AllDirectories))
{
cancellationToken.ThrowIfCancellationRequested();
try
{
File.SetAttributes(subDirectory, FileAttributes.Normal);
}
catch
{
// Best effort.
}
}
File.SetAttributes(directory, FileAttributes.Normal);
Directory.Delete(directory, recursive: true);
}
private async Task InstallToolDependencyAsync(
ToolDependency dependency,
IReadOnlyList<PackageIndexDocument> knownIndexes,
int step,
int totalSteps,
IProgress<InstallProgress> progress,
CancellationToken cancellationToken)
{
var target = _paths.GetToolVersionDirectory(dependency.Packager, dependency.Name, dependency.Version);
if (Directory.Exists(target) && Directory.EnumerateFileSystemEntries(target).Any())
{
ReportStep(progress, step, totalSteps, 100, $"Tool уже установлен: {dependency.Name} {dependency.Version}");
return;
}
var tool = knownIndexes
.SelectMany(x => x.Index.Packages)
.Where(x => string.Equals(x.Name, dependency.Packager, StringComparison.OrdinalIgnoreCase))
.SelectMany(x => x.Tools)
.FirstOrDefault(x =>
string.Equals(x.Name, dependency.Name, StringComparison.OrdinalIgnoreCase) &&
string.Equals(x.Version, dependency.Version, StringComparison.OrdinalIgnoreCase));
if (tool is null)
throw new InvalidOperationException($"Не нашёл tool {dependency.Packager}:{dependency.Name}@{dependency.Version} в загруженных index JSON.");
var system = HostMatcher.SelectBestSystem(tool.Systems);
var archive = new ArchiveItem(system.Url, system.ArchiveFileName, system.Checksum, system.Size);
var localArchive = await DownloadArchiveAsync(archive, step, totalSteps, $"Скачиваю tool {dependency.Name}", progress, cancellationToken);
await ExtractAndInstallAsync(localArchive, target, platformArchive: false, step, totalSteps, $"Устанавливаю tool {dependency.Name}", progress, cancellationToken);
}
private async Task InstallPlatformArchiveAsync(
PlatformDescriptor descriptor,
ArduinoPlatform platform,
int step,
int totalSteps,
IProgress<InstallProgress> progress,
CancellationToken cancellationToken)
{
var archive = new ArchiveItem(platform.Url, platform.ArchiveFileName, platform.Checksum, platform.Size);
var localArchive = await DownloadArchiveAsync(archive, step, totalSteps, $"Скачиваю {platform.Name} {platform.Version}", progress, cancellationToken);
var target = _paths.GetPlatformVersionDirectory(descriptor.PackageName, descriptor.Architecture, platform.Version);
await ExtractAndInstallAsync(localArchive, target, platformArchive: true, step, totalSteps, $"Устанавливаю {platform.Name}", progress, cancellationToken);
}
private async Task<string> DownloadArchiveAsync(
ArchiveItem item,
int step,
int totalSteps,
string status,
IProgress<InstallProgress> progress,
CancellationToken cancellationToken)
{
Directory.CreateDirectory(AppPaths.CacheDirectory);
var archiveFileName = !string.IsNullOrWhiteSpace(item.ArchiveFileName)
? item.ArchiveFileName
: GetFileNameFromUrl(item.Url);
var cacheFile = Path.Combine(AppPaths.CacheDirectory, $"{ShortHash(item.Url)}_{SanitizeFileName(archiveFileName)}");
if (File.Exists(cacheFile) && VerifySize(cacheFile, item.Size) && await VerifyChecksumAsync(cacheFile, item.Checksum, cancellationToken))
{
ReportStep(progress, step, totalSteps, 100, $"Из кэша: {archiveFileName}");
return cacheFile;
}
var tempFile = Path.Combine(
AppPaths.CacheDirectory,
$"{ShortHash(item.Url)}_{Guid.NewGuid():N}_{SanitizeFileName(archiveFileName)}.download");
try
{
ReportStep(progress, step, totalSteps, 0, $"{status}: подключаюсь к серверу...");
using var response = await GetResponseWithTimeoutAsync(item.Url, cancellationToken);
response.EnsureSuccessStatusCode();
var total = response.Content.Headers.ContentLength;
var buffer = new byte[1024 * 128];
long downloaded = 0;
int read;
await using (var input = await response.Content.ReadAsStreamAsync(cancellationToken))
await using (var output = new FileStream(tempFile, FileMode.CreateNew, FileAccess.Write, FileShare.None, buffer.Length, useAsync: true))
{
while ((read = await ReadWithIdleTimeoutAsync(input, buffer, archiveFileName, cancellationToken)) > 0)
{
await output.WriteAsync(buffer.AsMemory(0, read), cancellationToken);
downloaded += read;
var localPercent = total is > 0
? Math.Min(90, downloaded * 90.0 / total.Value)
: 25;
ReportStep(progress, step, totalSteps, localPercent, $"{status}: {archiveFileName} ({FormatBytes(downloaded)}{(total is > 0 ? " / " + FormatBytes(total.Value) : string.Empty)})");
}
await output.FlushAsync(cancellationToken);
}
if (!VerifySize(tempFile, item.Size))
throw new InvalidOperationException($"Размер архива {archiveFileName} не совпал с size из JSON.");
if (!await VerifyChecksumAsync(tempFile, item.Checksum, cancellationToken))
throw new InvalidOperationException($"Checksum архива {archiveFileName} не совпал с checksum из JSON.");
if (File.Exists(cacheFile))
File.Delete(cacheFile);
File.Move(tempFile, cacheFile);
}
catch
{
TryDeleteFile(tempFile);
throw;
}
ReportStep(progress, step, totalSteps, 100, $"Скачано: {archiveFileName}");
return cacheFile;
}
private async Task<HttpResponseMessage> GetResponseWithTimeoutAsync(string url, CancellationToken cancellationToken)
{
using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeoutCts.CancelAfter(ResponseHeaderTimeout);
try
{
return await _httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, timeoutCts.Token);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
throw new TimeoutException($"Сервер не ответил за {FormatTimeout(ResponseHeaderTimeout)}: {url}");
}
}
private static async Task<int> ReadWithIdleTimeoutAsync(Stream input, byte[] buffer, string archiveFileName, CancellationToken cancellationToken)
{
var readTask = input.ReadAsync(buffer.AsMemory(0, buffer.Length), cancellationToken).AsTask();
var timeoutTask = Task.Delay(DownloadIdleTimeout, cancellationToken);
var completed = await Task.WhenAny(readTask, timeoutTask);
if (completed == readTask)
return await readTask;
if (cancellationToken.IsCancellationRequested)
cancellationToken.ThrowIfCancellationRequested();
throw new TimeoutException($"Загрузка {archiveFileName} остановилась: за {FormatTimeout(DownloadIdleTimeout)} не получено новых данных.");
}
private async Task ExtractAndInstallAsync(
string archiveFile,
string targetDirectory,
bool platformArchive,
int step,
int totalSteps,
string status,
IProgress<InstallProgress> progress,
CancellationToken cancellationToken)
{
var tempRoot = Path.Combine(Path.GetTempPath(), "ArduManager.Boards", Guid.NewGuid().ToString("N"));
var tempInstall = targetDirectory + ".installing-" + Guid.NewGuid().ToString("N");
try
{
Directory.CreateDirectory(tempRoot);
ReportStep(progress, step, totalSteps, 0, status + ": распаковка");
await _extractor.ExtractAsync(archiveFile, tempRoot, cancellationToken);
var contentRoot = ArchiveExtractor.FindContentRoot(tempRoot, platformArchive);
Directory.CreateDirectory(Path.GetDirectoryName(targetDirectory)!);
CopyDirectory(contentRoot, tempInstall, cancellationToken);
if (Directory.Exists(targetDirectory))
Directory.Delete(targetDirectory, recursive: true);
Directory.Move(tempInstall, targetDirectory);
ReportStep(progress, step, totalSteps, 100, status + ": установлено");
}
finally
{
TryDeleteDirectory(tempRoot);
TryDeleteDirectory(tempInstall);
}
}
private static void CopyDirectory(string source, string destination, CancellationToken cancellationToken)
{
Directory.CreateDirectory(destination);
foreach (var directory in Directory.EnumerateDirectories(source, "*", SearchOption.AllDirectories))
{
cancellationToken.ThrowIfCancellationRequested();
var relative = Path.GetRelativePath(source, directory);
Directory.CreateDirectory(Path.Combine(destination, relative));
}
foreach (var file in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories))
{
cancellationToken.ThrowIfCancellationRequested();
var relative = Path.GetRelativePath(source, file);
var destFile = Path.Combine(destination, relative);
Directory.CreateDirectory(Path.GetDirectoryName(destFile)!);
File.Copy(file, destFile, overwrite: true);
}
}
private static void TryDeleteDirectory(string directory)
{
try
{
if (Directory.Exists(directory))
Directory.Delete(directory, recursive: true);
}
catch
{
// Best effort cleanup. The UI will still show the actual install error, if any.
}
}
private static void TryDeleteFile(string file)
{
try
{
if (File.Exists(file))
File.Delete(file);
}
catch
{
// Best effort cleanup.
}
}
private static void ReportStep(IProgress<InstallProgress> progress, int step, int totalSteps, double localPercent, string message)
{
var overall = Math.Clamp(((step * 100.0) + localPercent) / Math.Max(1, totalSteps), 0, 100);
progress.Report(new InstallProgress(message, overall));
}
private static bool VerifySize(string file, string? expectedSize)
{
if (string.IsNullOrWhiteSpace(expectedSize))
return true;
return long.TryParse(expectedSize, NumberStyles.Integer, CultureInfo.InvariantCulture, out var size)
&& new FileInfo(file).Length == size;
}
private static async Task<bool> VerifyChecksumAsync(string file, string? checksum, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(checksum))
return true;
var parts = checksum.Split(':', 2, StringSplitOptions.TrimEntries);
if (parts.Length != 2)
return false;
using HashAlgorithm algorithm = parts[0].ToUpperInvariant() switch
{
"SHA-256" or "SHA256" => SHA256.Create(),
"SHA-1" or "SHA1" => SHA1.Create(),
"MD5" => MD5.Create(),
_ => throw new InvalidOperationException($"Неподдерживаемый checksum algorithm: {parts[0]}")
};
await using var stream = File.OpenRead(file);
var actual = Convert.ToHexString(await algorithm.ComputeHashAsync(stream, cancellationToken));
return string.Equals(actual, parts[1].Replace(" ", ""), StringComparison.OrdinalIgnoreCase);
}
private static string ShortHash(string text)
{
var bytes = SHA1.HashData(System.Text.Encoding.UTF8.GetBytes(text));
return Convert.ToHexString(bytes).ToLowerInvariant()[..12];
}
private static string SanitizeFileName(string fileName)
{
foreach (var c in Path.GetInvalidFileNameChars())
fileName = fileName.Replace(c, '_');
return fileName;
}
private static string GetFileNameFromUrl(string url)
{
if (Uri.TryCreate(url, UriKind.Absolute, out var uri))
return Path.GetFileName(uri.LocalPath);
return "archive.bin";
}
private static string FormatTimeout(TimeSpan value)
{
return value.TotalSeconds >= 60
? $"{value.TotalMinutes:0.#} мин"
: $"{value.TotalSeconds:0} сек";
}
private static string FormatBytes(long value)
{
string[] units = { "B", "KB", "MB", "GB" };
double number = value;
var unit = 0;
while (number >= 1024 && unit < units.Length - 1)
{
number /= 1024;
unit++;
}
return $"{number:0.##} {units[unit]}";
}
private sealed record ArchiveItem(string Url, string ArchiveFileName, string? Checksum, string? Size);
}
@@ -0,0 +1,47 @@
using System.Text.Json;
using ArduboardsManager.App.Models;
namespace ArduboardsManager.App.Services;
public sealed class SettingsService
{
private static readonly JsonSerializerOptions JsonOptions = new() { WriteIndented = true };
public async Task<SettingsData> LoadAsync(CancellationToken cancellationToken = default)
{
Directory.CreateDirectory(AppPaths.AppDataDirectory);
if (!File.Exists(AppPaths.SettingsFile))
return new SettingsData();
await using var stream = File.OpenRead(AppPaths.SettingsFile);
var settings = await JsonSerializer.DeserializeAsync<SettingsData>(stream, JsonOptions, cancellationToken);
return settings ?? new SettingsData();
}
public async Task SaveAsync(SettingsData settings, CancellationToken cancellationToken = default)
{
Directory.CreateDirectory(AppPaths.AppDataDirectory);
await using var stream = File.Create(AppPaths.SettingsFile);
await JsonSerializer.SerializeAsync(stream, settings, JsonOptions, cancellationToken);
}
public async Task AddUrlAsync(string url, CancellationToken cancellationToken = default)
{
var settings = await LoadAsync(cancellationToken);
if (!settings.PackageUrls.Any(x => string.Equals(x, url, StringComparison.OrdinalIgnoreCase)))
{
settings.PackageUrls.Add(url);
await SaveAsync(settings, cancellationToken);
}
}
public async Task RemoveUrlAsync(string url, CancellationToken cancellationToken = default)
{
var settings = await LoadAsync(cancellationToken);
settings.PackageUrls = settings.PackageUrls
.Where(x => !string.Equals(x, url, StringComparison.OrdinalIgnoreCase))
.ToList();
await SaveAsync(settings, cancellationToken);
}
}
@@ -0,0 +1,43 @@
using ArduboardsManager.App.Models;
namespace ArduboardsManager.App.Services;
public sealed class StandardPlatformLinksService
{
private const string FileName = "standard-platforms.json";
public IReadOnlyList<StandardPlatformLink> Load()
{
var filePath = Path.Combine(AppContext.BaseDirectory, FileName);
// При dotnet run файл копируется в bin. На случай запуска из другой структуры оставляем fallback.
if (!File.Exists(filePath))
{
var sourceTreeFallback = Path.Combine(Environment.CurrentDirectory, "src", "ArduManager.App", FileName);
if (File.Exists(sourceTreeFallback))
filePath = sourceTreeFallback;
}
if (!File.Exists(filePath))
return Array.Empty<StandardPlatformLink>();
var json = File.ReadAllText(filePath);
var map = JsonSerializer.Deserialize<Dictionary<string, string>>(json, new JsonSerializerOptions
{
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true
});
if (map is null || map.Count == 0)
return Array.Empty<StandardPlatformLink>();
return map
.Where(x => !string.IsNullOrWhiteSpace(x.Key) && !string.IsNullOrWhiteSpace(x.Value))
.Select(x => new StandardPlatformLink
{
Name = x.Key.Trim(),
Url = x.Value.Trim()
})
.ToList();
}
}
@@ -0,0 +1,110 @@
namespace ArduboardsManager.App.Services;
public sealed class StartupCleanupService
{
private readonly ArduinoPathService _paths;
public StartupCleanupService(ArduinoPathService paths)
{
_paths = paths;
}
public void CleanupLeftovers()
{
CleanupDownloadFiles();
CleanupTempExtractionRoot();
CleanupInstallingDirectories();
}
private static void CleanupDownloadFiles()
{
try
{
if (!Directory.Exists(AppPaths.CacheDirectory))
return;
var deleted = 0;
foreach (var file in Directory.EnumerateFiles(AppPaths.CacheDirectory, "*.download", SearchOption.AllDirectories))
{
if (TryDeleteFile(file))
deleted++;
}
if (deleted > 0)
LogService.Info($"Startup cleanup: deleted partial downloads: {deleted}");
}
catch (Exception ex)
{
LogService.Error("Startup cleanup: partial downloads cleanup failed", ex);
}
}
private static void CleanupTempExtractionRoot()
{
try
{
var tempRoot = Path.Combine(Path.GetTempPath(), "ArduManager.Boards");
if (!Directory.Exists(tempRoot))
return;
Directory.Delete(tempRoot, recursive: true);
LogService.Info($"Startup cleanup: deleted temp extraction root: {tempRoot}");
}
catch (Exception ex)
{
LogService.Error("Startup cleanup: temp extraction cleanup failed", ex);
}
}
private void CleanupInstallingDirectories()
{
try
{
var packagesDirectory = Path.Combine(_paths.DataDirectory, "packages");
if (!Directory.Exists(packagesDirectory))
return;
var deleted = 0;
foreach (var directory in Directory.EnumerateDirectories(packagesDirectory, "*.installing-*", SearchOption.AllDirectories))
{
if (TryDeleteDirectory(directory))
deleted++;
}
if (deleted > 0)
LogService.Info($"Startup cleanup: deleted stale install directories: {deleted}");
}
catch (Exception ex)
{
LogService.Error("Startup cleanup: install directory cleanup failed", ex);
}
}
private static bool TryDeleteFile(string file)
{
try
{
if (File.Exists(file))
File.Delete(file);
return true;
}
catch
{
return false;
}
}
private static bool TryDeleteDirectory(string directory)
{
try
{
if (Directory.Exists(directory))
Directory.Delete(directory, recursive: true);
return true;
}
catch
{
return false;
}
}
}
@@ -0,0 +1,57 @@
using System.Text.RegularExpressions;
namespace ArduboardsManager.App.Services;
public sealed class VersionTextComparer : IComparer<string>
{
public static VersionTextComparer Instance { get; } = new();
private VersionTextComparer()
{
}
public int Compare(string? x, string? y)
{
if (ReferenceEquals(x, y)) return 0;
if (x is null) return -1;
if (y is null) return 1;
var xp = SplitVersion(x);
var yp = SplitVersion(y);
var count = Math.Max(xp.Count, yp.Count);
for (var i = 0; i < count; i++)
{
var xs = i < xp.Count ? xp[i] : "0";
var ys = i < yp.Count ? yp[i] : "0";
var xIsNumber = long.TryParse(xs, out var xn);
var yIsNumber = long.TryParse(ys, out var yn);
int result;
if (xIsNumber && yIsNumber)
result = xn.CompareTo(yn);
else
result = string.Compare(xs, ys, StringComparison.OrdinalIgnoreCase);
if (result != 0)
return result;
}
return string.Compare(x, y, StringComparison.OrdinalIgnoreCase);
}
public static bool IsGreaterThan(string? left, string? right)
{
if (string.IsNullOrWhiteSpace(left)) return false;
if (string.IsNullOrWhiteSpace(right)) return true;
return Instance.Compare(left, right) > 0;
}
private static List<string> SplitVersion(string version)
{
return Regex.Matches(version, @"\d+|[A-Za-z]+")
.Select(x => x.Value)
.ToList();
}
}
@@ -0,0 +1,54 @@
using System.Windows;
using System.Windows.Input;
using ArduboardsManager.App.Services;
namespace ArduboardsManager.App.ViewModels;
public sealed class AsyncRelayCommand : ICommand
{
private readonly Func<Task> _execute;
private readonly Func<bool>? _canExecute;
private bool _isExecuting;
public AsyncRelayCommand(Func<Task> execute, Func<bool>? canExecute = null)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object? parameter)
{
return !_isExecuting && (_canExecute?.Invoke() ?? true);
}
public async void Execute(object? parameter)
{
if (!CanExecute(parameter))
return;
try
{
_isExecuting = true;
RaiseCanExecuteChanged();
await _execute();
}
catch (Exception ex)
{
LogService.Error("Command execution failed", ex);
MessageBox.Show(
$"Ошибка выполнения команды. Подробности записаны в лог:\n{AppPaths.CurrentLogFile}\n\n{ex.Message}",
"ArduManager",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
finally
{
_isExecuting = false;
RaiseCanExecuteChanged();
}
}
public event EventHandler? CanExecuteChanged;
public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
@@ -0,0 +1,497 @@
using System.Collections.ObjectModel;
using System.Windows;
using ArduboardsManager.App.Models;
using ArduboardsManager.App.Services;
namespace ArduboardsManager.App.ViewModels;
public sealed class MainViewModel : ObservableObject
{
private readonly SettingsService _settingsService = new();
private readonly PackageIndexService _indexService = new();
private readonly ArduinoPathService _pathService = new();
private readonly PackageInstaller _installer;
private readonly StandardPlatformLinksService _standardPlatformLinksService = new();
private const string ArduinoOfficialIndexUrl = "https://downloads.arduino.cc/packages/package_index.json";
private readonly List<PackageIndexDocument> _knownIndexes = new();
private readonly List<PackageIndexDocument> _dependencyIndexes = new();
public event Action<string>? StatusChanged;
public event Action<bool>? BusyChanged;
public event Action<string>? LogMessage;
private string _newPackageUrl = string.Empty;
private StandardPlatformLink? _selectedStandardPlatform;
private string _footerText = "Готово";
private bool _isLoading;
public MainViewModel()
{
_installer = new PackageInstaller(_pathService);
AddUrlCommand = new AsyncRelayCommand(AddUrlAsync, () => !IsLoading && !string.IsNullOrWhiteSpace(NewPackageUrl));
ReloadCommand = new AsyncRelayCommand(ReloadAsync, () => !IsLoading);
StandardPlatforms.Add(new StandardPlatformLink { Name = "Популярные", Url = string.Empty });
foreach (var link in _standardPlatformLinksService.Load())
StandardPlatforms.Add(link);
_selectedStandardPlatform = StandardPlatforms.FirstOrDefault();
}
public ObservableCollection<PlatformCardViewModel> Platforms { get; } = new();
public ObservableCollection<StandardPlatformLink> StandardPlatforms { get; } = new();
public AsyncRelayCommand AddUrlCommand { get; }
public AsyncRelayCommand ReloadCommand { get; }
public string DataDirectory => $"Arduino15: {_pathService.DataDirectory}";
public string NewPackageUrl
{
get => _newPackageUrl;
set
{
if (SetProperty(ref _newPackageUrl, value))
AddUrlCommand.RaiseCanExecuteChanged();
}
}
public StandardPlatformLink? SelectedStandardPlatform
{
get => _selectedStandardPlatform;
set
{
if (!SetProperty(ref _selectedStandardPlatform, value))
return;
if (value is null || string.IsNullOrWhiteSpace(value.Url))
return;
_ = AddStandardPlatformAsync(value);
}
}
public string FooterText
{
get => _footerText;
set
{
if (SetProperty(ref _footerText, value))
StatusChanged?.Invoke(value);
}
}
public bool IsLoading
{
get => _isLoading;
set
{
if (SetProperty(ref _isLoading, value))
{
AddUrlCommand.RaiseCanExecuteChanged();
ReloadCommand.RaiseCanExecuteChanged();
BusyChanged?.Invoke(value);
}
}
}
private void ReportStatus(string message, bool writeLog = false)
{
FooterText = message;
if (writeLog)
Log(message);
}
private void Log(string message)
{
LogService.Info(message);
LogMessage?.Invoke(message);
}
public async Task InitializeAsync()
{
await ReloadAsync();
}
private Task AddUrlAsync()
{
return AddUrlFromInputAsync(NewPackageUrl);
}
private async Task AddStandardPlatformAsync(StandardPlatformLink link)
{
if (IsLoading)
{
ResetStandardPlatformSelection();
return;
}
NewPackageUrl = link.Url;
await AddUrlFromInputAsync(link.Url);
ResetStandardPlatformSelection();
}
private async Task AddUrlFromInputAsync(string rawUrl)
{
var url = rawUrl.Trim();
if (string.IsNullOrWhiteSpace(url))
return;
IsLoading = true;
ReportStatus("Проверяю package index...");
try
{
// Важно: сначала пробуем скачать и распарсить JSON. Только после успеха запоминаем ссылку.
await _indexService.DownloadAsync(url);
await _settingsService.AddUrlAsync(url);
Log($"Добавлена ссылка платформ: {url}");
NewPackageUrl = string.Empty;
await ReloadInternalAsync();
}
catch (Exception ex)
{
ReportStatus("Не удалось добавить ссылку.", writeLog: true);
MessageBox.Show(ex.Message, "Ошибка добавления package index", MessageBoxButton.OK, MessageBoxImage.Error);
}
finally
{
IsLoading = false;
}
}
private void ResetStandardPlatformSelection()
{
SelectedStandardPlatform = StandardPlatforms.FirstOrDefault();
}
private async Task ReloadAsync()
{
IsLoading = true;
try
{
await ReloadInternalAsync();
}
finally
{
IsLoading = false;
}
}
private async Task ReloadInternalAsync()
{
Platforms.Clear();
_knownIndexes.Clear();
_dependencyIndexes.Clear();
var settings = await _settingsService.LoadAsync();
if (settings.PackageUrls.Count == 0)
{
ReportStatus("Добавь ссылку на package_*_index.json.");
return;
}
var errors = new List<string>();
ReportStatus($"Обновляю {settings.PackageUrls.Count} index JSON...");
foreach (var url in settings.PackageUrls.Distinct(StringComparer.OrdinalIgnoreCase))
{
try
{
var document = await _indexService.DownloadAsync(url);
_knownIndexes.Add(document);
}
catch (Exception ex)
{
errors.Add($"{url}: {ex.Message}");
}
}
BuildCards();
var status = errors.Count == 0
? $"Загружено index JSON: {_knownIndexes.Count}. Платформ: {Platforms.Count}."
: $"Загружено index JSON: {_knownIndexes.Count}. Ошибки: {errors.Count}. Первая: {errors[0]}";
ReportStatus(status, writeLog: errors.Count > 0);
}
private void BuildCards()
{
var entries = _knownIndexes
.SelectMany(document => document.Index.Packages.SelectMany(package => package.Platforms.Select(platform => new
{
document.SourceUrl,
Package = package,
Platform = platform
})))
.Where(x => !string.IsNullOrWhiteSpace(x.Package.Name)
&& !string.IsNullOrWhiteSpace(x.Platform.Architecture)
&& !string.IsNullOrWhiteSpace(x.Platform.Version));
var groups = entries.GroupBy(x => new
{
x.SourceUrl,
PackageName = x.Package.Name,
x.Platform.Architecture
});
foreach (var group in groups)
{
var versions = group
.GroupBy(x => x.Platform.Version)
.ToDictionary(x => x.Key, x => x.First().Platform);
if (versions.Count == 0)
continue;
var sortedVersions = versions.Keys
.OrderByDescending(x => x, VersionTextComparer.Instance)
.ToList();
var latestVersion = sortedVersions[0];
var latestPlatform = versions[latestVersion];
var descriptor = new PlatformDescriptor
{
SourceUrl = group.Key.SourceUrl,
PackageName = group.Key.PackageName,
Architecture = group.Key.Architecture,
DisplayName = string.IsNullOrWhiteSpace(latestPlatform.Name)
? $"{group.Key.PackageName}:{group.Key.Architecture}"
: latestPlatform.Name,
GitHubUrl = ResolveGitHubUrl(
group.Select(x => x.Package.WebsiteUrl)
.Concat(group.Select(x => x.Platform.Url))
.Concat(new[] { group.Key.SourceUrl })),
PlatformsByVersion = versions
};
var installed = _pathService.GetInstalledPlatformVersion(descriptor.PackageName, descriptor.Architecture);
Platforms.Add(new PlatformCardViewModel(
descriptor,
sortedVersions,
installed,
latestVersion,
InstallCardAsync,
RemoveCardAsync));
}
}
private static string? ResolveGitHubUrl(IEnumerable<string?> candidates)
{
foreach (var candidate in candidates)
{
var normalized = NormalizeGitHubUrl(candidate);
if (!string.IsNullOrWhiteSpace(normalized))
return normalized;
}
return null;
}
private static string? NormalizeGitHubUrl(string? url)
{
if (string.IsNullOrWhiteSpace(url))
return null;
if (!Uri.TryCreate(url.Trim(), UriKind.Absolute, out var uri))
return null;
var host = uri.Host.ToLowerInvariant();
var segments = uri.AbsolutePath
.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (host == "github.com" || host == "www.github.com")
{
if (segments.Length >= 2)
return $"https://github.com/{segments[0]}/{segments[1]}";
return uri.GetLeftPart(UriPartial.Authority);
}
if (host == "raw.githubusercontent.com" && segments.Length >= 2)
return $"https://github.com/{segments[0]}/{segments[1]}";
return null;
}
private async Task EnsureDependencyIndexesLoadedAsync(ArduinoPlatform platform)
{
var dependencies = platform.ToolsDependencies ?? new List<ToolDependency>();
if (dependencies.Count == 0)
return;
var allIndexes = _knownIndexes.Concat(_dependencyIndexes).ToList();
var missing = dependencies
.Where(dependency => !ContainsTool(allIndexes, dependency))
.ToList();
if (missing.Count == 0)
return;
var needsArduinoIndex = missing.Any(dependency =>
string.Equals(dependency.Packager, "arduino", StringComparison.OrdinalIgnoreCase));
if (needsArduinoIndex && !HasIndexLoaded(ArduinoOfficialIndexUrl))
{
try
{
ReportStatus("Загружаю Arduino index для зависимостей...");
Log($"Загружаю dependency index: {ArduinoOfficialIndexUrl}");
var arduinoIndex = await _indexService.DownloadAsync(ArduinoOfficialIndexUrl);
_dependencyIndexes.Add(arduinoIndex);
allIndexes = _knownIndexes.Concat(_dependencyIndexes).ToList();
missing = dependencies
.Where(dependency => !ContainsTool(allIndexes, dependency))
.ToList();
}
catch (Exception ex)
{
var missingText = FormatMissingTools(missing);
throw new InvalidOperationException(
"Платформе нужны инструменты из Arduino package index, но его не удалось загрузить. " +
"Добавь Arduino official в список платформ или используй зеркало package_index.json, где есть эти tools.\n\n" +
$"Не найдены: {missingText}\n\n" +
$"Ошибка загрузки Arduino index: {ex.Message}", ex);
}
}
if (missing.Count > 0)
{
throw new InvalidOperationException(
"Платформе нужны tools, которых нет в загруженных package index JSON. " +
"Добавь package index, где они описаны, или его зеркало.\n\n" +
$"Не найдены: {FormatMissingTools(missing)}");
}
}
private bool HasIndexLoaded(string sourceUrl)
{
return _knownIndexes.Concat(_dependencyIndexes).Any(document =>
string.Equals(document.SourceUrl, sourceUrl, StringComparison.OrdinalIgnoreCase));
}
private static bool ContainsTool(IEnumerable<PackageIndexDocument> indexes, ToolDependency dependency)
{
return indexes
.SelectMany(document => document.Index.Packages)
.Where(package => string.Equals(package.Name, dependency.Packager, StringComparison.OrdinalIgnoreCase))
.SelectMany(package => package.Tools)
.Any(tool =>
string.Equals(tool.Name, dependency.Name, StringComparison.OrdinalIgnoreCase) &&
string.Equals(tool.Version, dependency.Version, StringComparison.OrdinalIgnoreCase));
}
private static string FormatMissingTools(IEnumerable<ToolDependency> dependencies)
{
return string.Join(", ", dependencies
.Select(dependency => $"{dependency.Packager}:{dependency.Name}@{dependency.Version}")
.Distinct(StringComparer.OrdinalIgnoreCase));
}
private async Task InstallCardAsync(PlatformCardViewModel card)
{
if (string.IsNullOrWhiteSpace(card.SelectedVersion))
return;
IsLoading = true;
card.IsBusy = true;
card.ProgressValue = 0;
card.Status = "Старт установки...";
ReportStatus($"Начата установка платформы {card.Descriptor.DisplayName}...");
Log($"Установка платформы: {card.Descriptor.Key}@{card.SelectedVersion}");
try
{
var progress = new Progress<InstallProgress>(p =>
{
card.ProgressValue = p.Percent;
card.Status = p.Message;
});
var platform = card.Descriptor.GetPlatform(card.SelectedVersion);
await EnsureDependencyIndexesLoadedAsync(platform);
var indexesForInstall = _knownIndexes.Concat(_dependencyIndexes).ToList();
await _installer.InstallAsync(card.Descriptor, card.SelectedVersion, indexesForInstall, progress);
var latest = card.Versions.FirstOrDefault() ?? card.SelectedVersion;
var installed = _pathService.GetInstalledPlatformVersion(card.Descriptor.PackageName, card.Descriptor.Architecture);
card.RefreshInstalledState(installed, latest);
card.ProgressValue = 100;
card.Status = "Установка завершена. Перезапусти Arduino IDE.";
ReportStatus($"Установлена платформа {card.Descriptor.DisplayName}.");
Log($"Платформа установлена: {card.Descriptor.Key}@{card.SelectedVersion}");
}
catch (Exception ex)
{
LogService.Error($"Install failed: {card.Descriptor.Key}@{card.SelectedVersion}", ex);
card.Status = "Ошибка: " + ex.Message;
ReportStatus("Ошибка установки платформы: " + ex.Message, writeLog: true);
MessageBox.Show(ex.Message, "Ошибка установки", MessageBoxButton.OK, MessageBoxImage.Error);
}
finally
{
card.IsBusy = false;
IsLoading = false;
}
}
private async Task RemoveCardAsync(PlatformCardViewModel card)
{
var hasInstalledVersion = !string.IsNullOrWhiteSpace(card.InstalledVersion);
var hasLocalFiles = _pathService.HasAnyLocalFilesForDescriptor(card.Descriptor);
var shouldDeleteLocalFiles = hasInstalledVersion || hasLocalFiles;
var platformName = card.Descriptor.DisplayName;
var message = shouldDeleteLocalFiles
? $"Удалить файлы платформы {platformName}?"
: $"Удалить поддержку платформы {platformName}?\n\n" +
"Если платформа содержит несколько плат, они тоже будут удалены из списка.";
var result = MessageBox.Show(message, "Удаление", MessageBoxButton.YesNo, MessageBoxImage.Warning);
if (result != MessageBoxResult.Yes)
return;
IsLoading = true;
card.IsBusy = true;
card.Status = shouldDeleteLocalFiles ? "Удаляю локальные файлы платформы..." : "Удаляю ссылку и карточку...";
ReportStatus(shouldDeleteLocalFiles ? $"Начато удаление платформы {card.Descriptor.DisplayName}..." : $"Удаляется поддержка платформы {card.Descriptor.DisplayName}...");
Log(shouldDeleteLocalFiles
? $"Удаление файлов платформы: {card.Descriptor.Key}"
: $"Удаление поддержки платформы: {card.Descriptor.Key}");
try
{
if (shouldDeleteLocalFiles)
{
await _installer.DeletePlatformAsync(card.Descriptor, _knownIndexes);
var latest = card.Versions.FirstOrDefault() ?? card.SelectedVersion ?? string.Empty;
card.RefreshInstalledState(null, latest);
card.ProgressValue = 0;
card.Status = string.Empty;
ReportStatus($"Удалена платформа {card.Descriptor.DisplayName}.");
Log($"Файлы платформы удалены: {card.Descriptor.Key}");
}
else
{
await _settingsService.RemoveUrlAsync(card.Descriptor.SourceUrl);
Log($"Поддержка платформы удалена: {card.Descriptor.Key}");
await ReloadInternalAsync();
}
}
catch (Exception ex)
{
card.Status = "Ошибка: " + ex.Message;
ReportStatus("Ошибка удаления платформы: " + ex.Message, writeLog: true);
MessageBox.Show(ex.Message, "Ошибка удаления", MessageBoxButton.OK, MessageBoxImage.Error);
}
finally
{
card.IsBusy = false;
IsLoading = false;
}
}
}
@@ -0,0 +1,24 @@
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace ArduboardsManager.App.ViewModels;
public abstract class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value))
return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
@@ -0,0 +1,178 @@
using System.Collections.ObjectModel;
using ArduboardsManager.App.Models;
namespace ArduboardsManager.App.ViewModels;
public sealed class PlatformCardViewModel : ObservableObject
{
private string? _selectedVersion;
private string? _installedVersion;
private string _latestVersion;
private bool _hasUpdate;
private bool _isBusy;
private double _progressValue;
private string _status = string.Empty;
public PlatformCardViewModel(
PlatformDescriptor descriptor,
IReadOnlyList<string> versions,
string? installedVersion,
string latestVersion,
Func<PlatformCardViewModel, Task> install,
Func<PlatformCardViewModel, Task> remove)
{
Descriptor = descriptor;
Versions = new ObservableCollection<string>(versions);
_installedVersion = installedVersion;
_latestVersion = latestVersion;
_hasUpdate = Services.VersionTextComparer.IsGreaterThan(latestVersion, installedVersion);
_selectedVersion = latestVersion;
InstallCommand = new AsyncRelayCommand(() => install(this), CanRunMainAction);
RemoveCommand = new AsyncRelayCommand(() => remove(this), CanRunMainAction);
Status = string.Empty;
}
public PlatformDescriptor Descriptor { get; }
public ObservableCollection<string> Versions { get; }
public AsyncRelayCommand InstallCommand { get; }
public AsyncRelayCommand RemoveCommand { get; }
public string Title => Descriptor.DisplayName;
public string Subtitle => Descriptor.Key;
public string? GitHubUrl => Descriptor.GitHubUrl;
public bool HasGitHubUrl => !string.IsNullOrWhiteSpace(GitHubUrl);
public string GitHubLinkText => FormatGitHubLinkText(GitHubUrl);
public string VersionBadge
{
get
{
if (string.IsNullOrWhiteSpace(InstalledVersion))
return "(не установлена)";
return HasUpdate
? $"v{InstalledVersion} (есть обновление)"
: $"v{InstalledVersion}";
}
}
public bool HasStatus => !string.IsNullOrWhiteSpace(Status);
public string? SelectedVersion
{
get => _selectedVersion;
set
{
if (SetProperty(ref _selectedVersion, value))
InstallCommand.RaiseCanExecuteChanged();
}
}
public string? InstalledVersion
{
get => _installedVersion;
private set
{
if (SetProperty(ref _installedVersion, value))
{
OnPropertyChanged(nameof(CurrentVersionText));
OnPropertyChanged(nameof(VersionBadge));
InstallCommand.RaiseCanExecuteChanged();
}
}
}
public string LatestVersion
{
get => _latestVersion;
private set
{
if (SetProperty(ref _latestVersion, value))
{
OnPropertyChanged(nameof(CurrentVersionText));
OnPropertyChanged(nameof(VersionBadge));
}
}
}
public bool HasUpdate
{
get => _hasUpdate;
private set
{
if (SetProperty(ref _hasUpdate, value))
{
OnPropertyChanged(nameof(CurrentVersionText));
OnPropertyChanged(nameof(VersionBadge));
}
}
}
public string CurrentVersionText
{
get
{
if (string.IsNullOrWhiteSpace(InstalledVersion))
return "не установлена";
return HasUpdate
? $"текущая: {InstalledVersion} (есть обновление: {LatestVersion})"
: $"текущая: {InstalledVersion}";
}
}
public bool IsBusy
{
get => _isBusy;
set
{
if (SetProperty(ref _isBusy, value))
{
InstallCommand.RaiseCanExecuteChanged();
RemoveCommand.RaiseCanExecuteChanged();
}
}
}
public double ProgressValue
{
get => _progressValue;
set => SetProperty(ref _progressValue, value);
}
public string Status
{
get => _status;
set
{
if (SetProperty(ref _status, value))
OnPropertyChanged(nameof(HasStatus));
}
}
public void RefreshInstalledState(string? installedVersion, string latestVersion)
{
InstalledVersion = installedVersion;
LatestVersion = latestVersion;
HasUpdate = Services.VersionTextComparer.IsGreaterThan(latestVersion, installedVersion);
}
private static string FormatGitHubLinkText(string? url)
{
if (string.IsNullOrWhiteSpace(url))
return string.Empty;
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
return url;
var text = uri.Host + uri.AbsolutePath.TrimEnd('/');
return text.StartsWith("www.", StringComparison.OrdinalIgnoreCase) ? text[4..] : text;
}
private bool CanRunMainAction()
{
return !IsBusy && !string.IsNullOrWhiteSpace(SelectedVersion);
}
}
@@ -0,0 +1,23 @@
using System.Windows.Input;
namespace ArduboardsManager.App.ViewModels;
public sealed class RelayCommand : ICommand
{
private readonly Action _execute;
private readonly Func<bool>? _canExecute;
public RelayCommand(Action execute, Func<bool>? canExecute = null)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object? parameter) => _canExecute?.Invoke() ?? true;
public void Execute(object? parameter) => _execute();
public event EventHandler? CanExecuteChanged;
public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
@@ -10,3 +10,9 @@ global using System.Threading.Tasks;
global using System.Text;
global using System.Text.Json;
global using System.ComponentModel;
global using System.Globalization;
global using System.Runtime.CompilerServices;
global using System.Security.Cryptography;
global using System.Text.Json.Serialization;
global using System.Text.RegularExpressions;
@@ -1,6 +1,6 @@
using System.Windows.Input;
namespace ArdulibsManager.Infrastructure;
namespace ArduManager.Infrastructure;
public sealed class AsyncRelayCommand : ICommand
{
@@ -1,7 +1,7 @@
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace ArdulibsManager.Infrastructure;
namespace ArduManager.Infrastructure;
public abstract class ObservableObject : INotifyPropertyChanged
{
@@ -1,6 +1,6 @@
using System.Windows.Input;
namespace ArdulibsManager.Infrastructure;
namespace ArduManager.Infrastructure;
public sealed class RelayCommand : ICommand
{
@@ -1,4 +1,4 @@
namespace ArdulibsManager.Models;
namespace ArduManager.Models;
public sealed class AppSettings
{
@@ -1,4 +1,4 @@
namespace ArdulibsManager.Models;
namespace ArduManager.Models;
public sealed class DependencyPlanItem
{
@@ -1,4 +1,4 @@
namespace ArdulibsManager.Models;
namespace ArduManager.Models;
public sealed class GithubRepository
{
@@ -1,4 +1,4 @@
namespace ArdulibsManager.Models;
namespace ArduManager.Models;
public sealed class GithubTag
{
@@ -0,0 +1,167 @@
using ArduManager.Infrastructure;
namespace ArduManager.Models;
public sealed class InstalledLibrary : ObservableObject
{
private string? _latestVersion;
private bool _isChecking;
private bool _hasUpdate;
private string? _status;
private string? _updateRepositoryFullName;
public required string Name { get; init; }
public string? Version { get; init; }
public string? PropertiesVersion { get; init; }
public string? InstalledRef { get; init; }
public string? Maintainer { get; init; }
public string? Url { get; init; }
public required string LocalPath { get; init; }
public string? RepositoryFullName { get; init; }
public string? UpdateRepositoryFullName
{
get => _updateRepositoryFullName;
set
{
if (SetProperty(ref _updateRepositoryFullName, value))
NotifyGitHubLinkChanged();
}
}
public string? LatestVersion
{
get => _latestVersion;
set
{
if (SetProperty(ref _latestVersion, value))
OnPropertyChanged(nameof(VersionBadge));
}
}
public bool HasUpdate
{
get => _hasUpdate;
set
{
if (SetProperty(ref _hasUpdate, value))
{
OnPropertyChanged(nameof(VersionBadge));
OnPropertyChanged(nameof(HasVisibleStatus));
}
}
}
public bool IsChecking
{
get => _isChecking;
set
{
if (SetProperty(ref _isChecking, value))
OnPropertyChanged(nameof(VersionBadge));
}
}
public string? Status
{
get => _status;
set
{
if (SetProperty(ref _status, value))
{
OnPropertyChanged(nameof(VersionBadge));
OnPropertyChanged(nameof(HasVisibleStatus));
}
}
}
public string VersionBadge
{
get
{
var version = string.IsNullOrWhiteSpace(Version) ? string.Empty : $" v{Version}";
if (IsChecking)
return string.IsNullOrWhiteSpace(version) ? " (проверка...)" : version + " (проверка...)";
if (HasUpdate)
return string.IsNullOrWhiteSpace(version) ? " (есть обновление)" : version + " (есть обновление)";
if (IsActualStatus(Status))
return string.IsNullOrWhiteSpace(version) ? " (актуальная)" : version + " (актуальная)";
return version;
}
}
public bool HasVisibleStatus
{
get
{
if (string.IsNullOrWhiteSpace(Status))
return false;
if (IsActualStatus(Status))
return false;
if (Status.StartsWith("Есть обновление", StringComparison.OrdinalIgnoreCase))
return false;
return true;
}
}
private static bool IsActualStatus(string? status)
{
return !string.IsNullOrWhiteSpace(status)
&& status.StartsWith("Актуально", StringComparison.OrdinalIgnoreCase);
}
public string? GitHubUrl
{
get
{
if (!string.IsNullOrWhiteSpace(UpdateRepositoryFullName))
return BuildGitHubUrl(UpdateRepositoryFullName);
if (!string.IsNullOrWhiteSpace(RepositoryFullName))
return BuildGitHubUrl(RepositoryFullName);
if (!string.IsNullOrWhiteSpace(Url) && Url.Contains("github.com", StringComparison.OrdinalIgnoreCase))
return Url;
return null;
}
}
public bool HasGitHubUrl => !string.IsNullOrWhiteSpace(GitHubUrl);
public string GitHubLinkText
{
get
{
var url = GitHubUrl;
if (string.IsNullOrWhiteSpace(url))
return string.Empty;
return url
.Replace("https://", string.Empty, StringComparison.OrdinalIgnoreCase)
.Replace("http://", string.Empty, StringComparison.OrdinalIgnoreCase)
.TrimEnd('/');
}
}
private static string? BuildGitHubUrl(string fullName)
{
var parts = fullName.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
return parts.Length == 2 ? $"https://github.com/{parts[0]}/{parts[1]}" : null;
}
private void NotifyGitHubLinkChanged()
{
OnPropertyChanged(nameof(GitHubUrl));
OnPropertyChanged(nameof(HasGitHubUrl));
OnPropertyChanged(nameof(GitHubLinkText));
}
}
@@ -1,4 +1,4 @@
namespace ArdulibsManager.Models;
namespace ArduManager.Models;
public sealed class LibraryProperties
{
@@ -1,4 +1,4 @@
namespace ArdulibsManager.Models;
namespace ArduManager.Models;
public sealed class ManagedLibraryMetadata
{
@@ -1,7 +1,7 @@
using System.Collections.ObjectModel;
using ArdulibsManager.Infrastructure;
using ArduManager.Infrastructure;
namespace ArdulibsManager.Models;
namespace ArduManager.Models;
public sealed class SearchResult : ObservableObject
{
@@ -18,6 +18,21 @@ public sealed class SearchResult : ObservableObject
public string Title => Repository.FullName;
public string Url => Repository.Url;
public string InstalledBadge
{
get
{
if (InstalledLibrary is null)
return string.Empty;
return string.IsNullOrWhiteSpace(InstalledLibrary.Version)
? " (установлена)"
: $" (установлена v{InstalledLibrary.Version})";
}
}
public bool HasStatus => !string.IsNullOrWhiteSpace(Status);
public ObservableCollection<GithubTag> Tags
{
get => _tags;
@@ -45,7 +60,11 @@ public sealed class SearchResult : ObservableObject
public bool IsInstalled
{
get => _isInstalled;
set => SetProperty(ref _isInstalled, value);
set
{
if (SetProperty(ref _isInstalled, value))
OnPropertyChanged(nameof(InstallButtonText));
}
}
public bool TagsLoaded
@@ -57,7 +76,11 @@ public sealed class SearchResult : ObservableObject
public InstalledLibrary? InstalledLibrary
{
get => _installedLibrary;
set => SetProperty(ref _installedLibrary, value);
set
{
if (SetProperty(ref _installedLibrary, value))
OnPropertyChanged(nameof(InstalledBadge));
}
}
public string InstallButtonText => IsInstalled ? "Изменить" : "Установить";
@@ -65,7 +88,11 @@ public sealed class SearchResult : ObservableObject
public string? Status
{
get => _status;
set => SetProperty(ref _status, value);
set
{
if (SetProperty(ref _status, value))
OnPropertyChanged(nameof(HasStatus));
}
}
public void RefreshInstallState(InstalledLibrary? installed)
@@ -73,5 +100,6 @@ public sealed class SearchResult : ObservableObject
InstalledLibrary = installed;
IsInstalled = installed is not null;
OnPropertyChanged(nameof(InstallButtonText));
OnPropertyChanged(nameof(InstalledBadge));
}
}
@@ -1,6 +1,6 @@
{
"profiles": {
"ArdulibsManager.App": {
"ArduManager.App": {
"commandName": "Project"
}
}
@@ -1,10 +1,10 @@
namespace ArdulibsManager.Services;
namespace ArduManager.Services;
public sealed class CacheService
{
public string AppCacheDir { get; } = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"ArdulibsManager",
"ArduManager",
"cache");
public CacheService() => Directory.CreateDirectory(AppCacheDir);
@@ -1,7 +1,7 @@
using System.IO.Compression;
using ArdulibsManager.Models;
using ArduManager.Models;
namespace ArdulibsManager.Services;
namespace ArduManager.Services;
public sealed class DependencyResolverService
{
@@ -82,7 +82,7 @@ public sealed class DependencyResolverService
var cacheKey = repo.FullName + "@" + tag;
if (_propsCache.TryGetValue(cacheKey, out var cached)) return cached;
var tempRoot = Path.Combine(Path.GetTempPath(), "ArdulibsManager", "deps", Guid.NewGuid().ToString("N"));
var tempRoot = Path.Combine(Path.GetTempPath(), "ArduManager", "deps", Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempRoot);
var zipPath = Path.Combine(tempRoot, "repo.zip");
var extractPath = Path.Combine(tempRoot, "extract");
@@ -2,9 +2,9 @@ using System.Net.Http;
using System.IO.Compression;
using System.Net.Http.Headers;
using System.Text.Json;
using ArdulibsManager.Models;
using ArduManager.Models;
namespace ArdulibsManager.Services;
namespace ArduManager.Services;
public sealed class GithubService
{
@@ -20,7 +20,7 @@ public sealed class GithubService
if (_http.Timeout == System.Threading.Timeout.InfiniteTimeSpan)
_http.Timeout = TimeSpan.FromSeconds(30);
_http.DefaultRequestHeaders.UserAgent.Clear();
_http.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("ArdulibsManager", "0.1"));
_http.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("ArduManager", "0.1"));
}
private HttpRequestMessage Request(HttpMethod method, string url)
@@ -1,7 +1,7 @@
using System.IO.Compression;
using ArdulibsManager.Models;
using ArduManager.Models;
namespace ArdulibsManager.Services;
namespace ArduManager.Services;
public sealed class LibraryInstallService
{
@@ -18,7 +18,7 @@ public sealed class LibraryInstallService
{
Directory.CreateDirectory(librariesPath);
var librariesRoot = Path.GetFullPath(librariesPath);
var tempRoot = Path.Combine(Path.GetTempPath(), "ArdulibsManager", Guid.NewGuid().ToString("N"));
var tempRoot = Path.Combine(Path.GetTempPath(), "ArduManager", Guid.NewGuid().ToString("N"));
var stagingPath = Path.Combine(librariesRoot, ".ardulibs-staging-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempRoot);
var zipPath = Path.Combine(tempRoot, "repo.zip");
@@ -1,6 +1,6 @@
using ArdulibsManager.Models;
using ArduManager.Models;
namespace ArdulibsManager.Services;
namespace ArduManager.Services;
public sealed class LibraryScannerService
{
@@ -24,15 +24,13 @@ public sealed class LibraryScannerService
var props = LibraryProperties.Parse(text);
var metadata = await ReadMetadataAsync(dir, ct);
var displayVersion = props.Version;
var status = metadata?.RepositoryFullName is null
? "Не проверено"
: $"Управляется: {metadata.RepositoryFullName}";
string? status = null;
if (!string.IsNullOrWhiteSpace(metadata?.InstalledRef)
&& !string.IsNullOrWhiteSpace(props.Version)
&& !VersionService.IsSameVersion(metadata.InstalledRef, props.Version))
{
status += $"; library.properties version={props.Version}";
status = $"library.properties version={props.Version}";
}
list.Add(new InstalledLibrary
@@ -1,9 +1,9 @@
using System.Net.Http;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using ArdulibsManager.Models;
using ArduManager.Models;
namespace ArdulibsManager.Services;
namespace ArduManager.Services;
public sealed class RepositoryRegistryService
{
@@ -1,13 +1,13 @@
using System.Text.Json;
using ArdulibsManager.Models;
using ArduManager.Models;
namespace ArdulibsManager.Services;
namespace ArduManager.Services;
public sealed class SettingsService
{
private readonly string _appDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"ArdulibsManager");
"ArduManager");
private string SettingsFile => Path.Combine(_appDir, "settings.json");
@@ -1,7 +1,7 @@
using System.Text.RegularExpressions;
using ArdulibsManager.Models;
using ArduManager.Models;
namespace ArdulibsManager.Services;
namespace ArduManager.Services;
public static class VersionService
{
@@ -1,12 +1,12 @@
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Windows;
using ArdulibsManager.Infrastructure;
using ArdulibsManager.Models;
using ArdulibsManager.Services;
using ArduManager.Infrastructure;
using ArduManager.Models;
using ArduManager.Services;
using Microsoft.Win32;
namespace ArdulibsManager.ViewModels;
namespace ArduManager.ViewModels;
public sealed class MainViewModel : ObservableObject
{
@@ -26,6 +26,7 @@ public sealed class MainViewModel : ObservableObject
private string _repositoryListUrl = AppSettings.DefaultRepositoryListUrl;
private string? _githubToken;
private bool _checkUpdatesOnStartup = true;
private readonly string _arduinoDataDirectory = new ArduboardsManager.App.Services.ArduinoPathService().DataDirectory;
public ObservableCollection<SearchResult> SearchResults { get; } = new();
public ObservableCollection<InstalledLibrary> InstalledLibraries { get; } = new();
@@ -65,6 +66,8 @@ public sealed class MainViewModel : ObservableObject
set => SetProperty(ref _checkUpdatesOnStartup, value);
}
public string ArduinoDataDirectory => _arduinoDataDirectory;
public string Status
{
get => _status;
@@ -89,6 +92,8 @@ public sealed class MainViewModel : ObservableObject
public AsyncRelayCommand UpdateAllCommand { get; }
public RelayCommand BrowseLibrariesCommand { get; }
public RelayCommand OpenFolderCommand { get; }
public RelayCommand OpenLibraryGithubCommand { get; }
public RelayCommand OpenArduinoDataDirectoryCommand { get; }
public MainViewModel()
{
@@ -113,6 +118,8 @@ public sealed class MainViewModel : ObservableObject
UpdateAllCommand = new AsyncRelayCommand(UpdateAllWithUpdatesAsync);
BrowseLibrariesCommand = new RelayCommand(BrowseLibraries);
OpenFolderCommand = new RelayCommand(p => OpenFolder((p as InstalledLibrary)?.LocalPath ?? LibrariesPath));
OpenLibraryGithubCommand = new RelayCommand(p => OpenLibraryGithub(p as InstalledLibrary));
OpenArduinoDataDirectoryCommand = new RelayCommand(_ => OpenFolder(ArduinoDataDirectory));
}
private async Task InitializeAsync()
@@ -288,7 +295,7 @@ public sealed class MainViewModel : ObservableObject
private static string? GetInstalledComparableVersion(InstalledLibrary lib)
{
// Если библиотека установлена/обновлена через ArdulibsManager, сравниваем обновления
// Если библиотека установлена/обновлена через ArduManager, сравниваем обновления
// с выбранным GitHub ref из .ardulibs.json, а не только с version из library.properties.
// Некоторые библиотеки публикуют tag 1.1.2, но забывают обновить library.properties version.
return string.IsNullOrWhiteSpace(lib.InstalledRef) ? lib.Version : lib.InstalledRef;
@@ -299,7 +306,7 @@ public sealed class MainViewModel : ObservableObject
if (string.IsNullOrWhiteSpace(lib.Name))
return new UpdateCandidateResult(null, null, false, "Нет имени библиотеки");
// Если библиотека установлена ArdulibsManager, обновляем строго по сохранённому repo
// Если библиотека установлена ArduManager, обновляем строго по сохранённому repo
// из .ardulibs.json и не ищем совпадения в registry.
if (!string.IsNullOrWhiteSpace(lib.RepositoryFullName))
{
@@ -699,6 +706,60 @@ public sealed class MainViewModel : ObservableObject
}
}
public void SetPlatformStatus(string message, bool? isBusy = null)
{
if (!string.IsNullOrWhiteSpace(message))
Status = message;
if (isBusy.HasValue)
IsBusy = isBusy.Value;
}
public void AddPlatformLog(string message)
{
if (!string.IsNullOrWhiteSpace(message))
Log("Платформы: " + message);
}
public void RestoreLibraryStatus()
{
if (_libraryOperationLock.CurrentCount > 0)
IsBusy = false;
Status = InstalledLibraries.Count > 0
? $"Установлено библиотек: {InstalledLibraries.Count}"
: "Готово";
}
private void OpenLibraryGithub(InstalledLibrary? lib)
{
if (lib is null)
return;
var repo = ResolveRepositoryForInstalledLibrary(lib);
var url = repo?.Url;
if (string.IsNullOrWhiteSpace(url) && !string.IsNullOrWhiteSpace(lib.Url))
url = lib.Url;
if (string.IsNullOrWhiteSpace(url))
{
MessageBox.Show("Репозиторий GitHub для этой библиотеки не найден.", "GitHub", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
OpenUrl(url);
}
private static void OpenUrl(string url)
{
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
return;
Process.Start(new ProcessStartInfo(uri.AbsoluteUri) { UseShellExecute = true });
}
private static void OpenFolder(string path)
{
if (Directory.Exists(path))
+250
View File
@@ -0,0 +1,250 @@
<Window x:Class="ArduManager.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:ArduManager.ViewModels"
xmlns:views="clr-namespace:ArduManager.Views"
mc:Ignorable="d"
Title="Arduino Packet Manager" Height="560" Width="820"
WindowStartupLocation="CenterScreen"
Loaded="Window_Loaded">
<Window.DataContext>
<vm:MainViewModel />
</Window.DataContext>
<Window.InputBindings>
<KeyBinding Key="F5" Command="{Binding RescanCommand}" />
</Window.InputBindings>
<Window.Resources>
<Style x:Key="UnifiedCardBorderStyle" TargetType="Border">
<Setter Property="Background" Value="White" />
<Setter Property="BorderBrush" Value="#DDDDDD" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="8" />
<Setter Property="Padding" Value="6" />
<Setter Property="Margin" Value="0,0,0,4" />
</Style>
<Style x:Key="CardTitleTextStyle" TargetType="TextBlock">
<Setter Property="FontSize" Value="15" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="TextTrimming" Value="CharacterEllipsis" />
</Style>
<Style x:Key="CardVersionTextStyle" TargetType="TextBlock">
<Setter Property="FontSize" Value="13" />
<Setter Property="FontWeight" Value="Normal" />
<Setter Property="Foreground" Value="#4B5563" />
<Setter Property="Margin" Value="6,1,0,0" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="TextTrimming" Value="CharacterEllipsis" />
</Style>
<Style x:Key="CardSecondaryTextStyle" TargetType="TextBlock">
<Setter Property="FontSize" Value="11" />
<Setter Property="Foreground" Value="#666666" />
<Setter Property="Margin" Value="0,1,0,0" />
<Setter Property="TextTrimming" Value="CharacterEllipsis" />
</Style>
<Style x:Key="CardButtonStyle" TargetType="Button">
<Setter Property="Height" Value="30" />
<Setter Property="MinWidth" Value="92" />
<Setter Property="Padding" Value="12,0" />
<Setter Property="Margin" Value="4,0,0,0" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<Style x:Key="CardComboBoxStyle" TargetType="ComboBox">
<Setter Property="Height" Value="30" />
<Setter Property="Width" Value="105" />
<Setter Property="MinWidth" Value="105" />
<Setter Property="Padding" Value="5,0" />
<Setter Property="Margin" Value="4,0,0,0" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
</Style>
</Window.Resources>
<DockPanel>
<Border DockPanel.Dock="Bottom" Background="#F5F5F5" BorderBrush="#DDD" BorderThickness="1,1,0,0" Padding="10">
<DockPanel>
<TextBlock Text="{Binding Status}" VerticalAlignment="Center" />
<ProgressBar DockPanel.Dock="Right" Width="160" Height="14" IsIndeterminate="{Binding IsBusy}" Margin="12,0,0,0" />
</DockPanel>
</Border>
<TabControl x:Name="MainTabControl" Margin="10" SelectionChanged="MainTabControl_SelectionChanged">
<TabItem Header="Поиск библиотек">
<Grid Margin="8">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Margin="0,0,0,8">
<Grid>
<TextBox x:Name="LibrarySearchTextBox"
Height="30"
FontSize="14"
VerticalContentAlignment="Center"
Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}"
ToolTip="Минимум 3 символа" />
<TextBlock Text="Название библиотеки"
Foreground="#9CA3AF"
FontSize="14"
Margin="12,0,0,0"
VerticalAlignment="Center"
IsHitTestVisible="False">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding Text, ElementName=LibrarySearchTextBox}" Value="">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Grid>
</StackPanel>
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto">
<ItemsControl ItemsSource="{Binding SearchResults}" Margin="0,0,8,0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Style="{StaticResource UnifiedCardBorderStyle}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel Orientation="Vertical" VerticalAlignment="Center" Margin="0,0,8,0">
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock Text="{Binding Title}" Style="{StaticResource CardTitleTextStyle}" MaxWidth="430" />
<TextBlock Text="{Binding InstalledBadge}" Style="{StaticResource CardVersionTextStyle}" />
</StackPanel>
<TextBlock Text="{Binding Status}"
Foreground="#A45"
FontSize="11"
Margin="0,1,0,0"
Visibility="{Binding HasStatus, Converter={StaticResource BoolToVisibility}}" />
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center" Margin="12,0,0,0">
<ComboBox Style="{StaticResource CardComboBoxStyle}"
ItemsSource="{Binding Tags}"
SelectedItem="{Binding SelectedTag}"
DisplayMemberPath="DisplayName"
DropDownOpened="VersionComboBox_DropDownOpened"
MaxDropDownHeight="220"
IsTextSearchEnabled="False"
ToolTip="Пока версия не выбрана, установка берёт latest GitHub tag" />
<Button Content="{Binding InstallButtonText}"
Style="{StaticResource CardButtonStyle}"
Command="{Binding DataContext.InstallCommand, RelativeSource={RelativeSource AncestorType=Window}}"
CommandParameter="{Binding}" />
</StackPanel>
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
</TabItem>
<TabItem Header="Библиотеки">
<Grid Margin="8">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Margin="0,0,0,8">
<Button Content="Обновить список" Width="150" Height="30" Command="{Binding RescanCommand}" />
<Button Content="Обновить библиотеки" Width="150" Height="30" Margin="8,0,0,0" Command="{Binding UpdateAllCommand}" />
</StackPanel>
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto">
<ItemsControl ItemsSource="{Binding InstalledLibraries}" Margin="0,0,8,0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Style="{StaticResource UnifiedCardBorderStyle}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel Orientation="Vertical" VerticalAlignment="Center" Margin="0,0,8,0">
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock Text="{Binding Name}" Style="{StaticResource CardTitleTextStyle}" MaxWidth="310" />
<TextBlock Text="{Binding VersionBadge}" Style="{StaticResource CardVersionTextStyle}" />
</StackPanel>
<TextBlock Style="{StaticResource CardSecondaryTextStyle}"
Visibility="{Binding HasGitHubUrl, Converter={StaticResource BoolToVisibility}}">
<Hyperlink NavigateUri="{Binding GitHubUrl}"
RequestNavigate="OpenHyperlink_RequestNavigate">
<Run Text="{Binding GitHubLinkText, Mode=OneWay}" />
</Hyperlink>
</TextBlock>
<TextBlock Text="{Binding Status}"
Foreground="#A45"
FontSize="11"
Margin="0,1,0,0"
TextWrapping="Wrap"
Visibility="{Binding HasVisibleStatus, Converter={StaticResource BoolToVisibility}}" />
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center" Margin="12,0,0,0">
<Button Content="Обновить" ToolTip="Установить свежую версию" Style="{StaticResource CardButtonStyle}" Command="{Binding DataContext.UpdateCommand, RelativeSource={RelativeSource AncestorType=Window}}" CommandParameter="{Binding}" />
<Button Content="Открыть" ToolTip="Открыть папку библиотеки" Style="{StaticResource CardButtonStyle}" Command="{Binding DataContext.OpenFolderCommand, RelativeSource={RelativeSource AncestorType=Window}}" CommandParameter="{Binding}" />
<Button Content="Удалить" ToolTip="Удалить библиотеку" Style="{StaticResource CardButtonStyle}" Command="{Binding DataContext.RemoveCommand, RelativeSource={RelativeSource AncestorType=Window}}" CommandParameter="{Binding}" />
</StackPanel>
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
</TabItem>
<TabItem x:Name="PlatformsTab" Header="Платформы">
<views:PlatformsView x:Name="PlatformsHost" />
</TabItem>
<TabItem Header="Настройки">
<StackPanel Margin="12" MaxWidth="760" HorizontalAlignment="Left">
<TextBlock Text="Папка Arduino libraries" FontWeight="SemiBold" />
<DockPanel>
<Button DockPanel.Dock="Right" Content="Выбрать" Width="86" Height="30" Command="{Binding BrowseLibrariesCommand}" />
<Button DockPanel.Dock="Right" Content="Открыть" Width="86" Height="30" Command="{Binding OpenFolderCommand}" Margin="4,0,4,0" />
<TextBox Height="30" VerticalContentAlignment="Center" Text="{Binding LibrariesPath, UpdateSourceTrigger=PropertyChanged}" />
</DockPanel>
<TextBlock Text="Папка Arduino15" FontWeight="SemiBold" Margin="4,16,4,0" />
<DockPanel>
<Button DockPanel.Dock="Right" Content="Открыть" Width="86" Height="30" Command="{Binding OpenArduinoDataDirectoryCommand}" />
<TextBox Height="30" VerticalContentAlignment="Center" Text="{Binding ArduinoDataDirectory, Mode=OneWay}" IsReadOnly="True" Background="#F5F5F5" Foreground="#555" />
</DockPanel>
<TextBlock Text="Реестр библиотек" FontWeight="SemiBold" Margin="4,16,4,0" />
<DockPanel>
<Button DockPanel.Dock="Right" Content="Обновить" Width="86" Height="30" Command="{Binding RefreshRegistryCommand}" />
<TextBox Height="30" VerticalContentAlignment="Center" Text="{Binding RepositoryListUrl, UpdateSourceTrigger=PropertyChanged}" />
</DockPanel>
<TextBlock Text="GitHub token (опционально, для повышения лимитов)" FontWeight="SemiBold" Margin="4,16,4,0" />
<TextBox Height="30" VerticalContentAlignment="Center" Text="{Binding GitHubToken, UpdateSourceTrigger=PropertyChanged}" Margin="0,0,0,12" />
<CheckBox Content="Проверять обновления при запуске" IsChecked="{Binding CheckUpdatesOnStartup}" Margin="4,0,4,12" />
<Button Content="Сохранить настройки" Width="180" HorizontalAlignment="Left" Command="{Binding SaveSettingsCommand}" />
</StackPanel>
</TabItem>
<TabItem Header="Лог">
<ListBox ItemsSource="{Binding Logs}" Margin="8" FontFamily="Consolas" />
</TabItem>
</TabControl>
</DockPanel>
</Window>
@@ -0,0 +1,53 @@
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using ArduManager.Models;
using ArduManager.ViewModels;
namespace ArduManager.Views;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (DataContext is MainViewModel vm)
vm.InitializeCommand.Execute(null);
}
private void MainTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (!ReferenceEquals(e.OriginalSource, MainTabControl))
return;
if (PlatformsHost is not null && DataContext is MainViewModel vm)
{
PlatformsHost.IsStatusActive = PlatformsTab?.IsSelected == true;
if (PlatformsHost.IsStatusActive)
vm.SetPlatformStatus(PlatformsHost.CurrentStatus, PlatformsHost.CurrentIsBusy);
else
vm.RestoreLibraryStatus();
}
}
private void VersionComboBox_DropDownOpened(object sender, EventArgs e)
{
if (DataContext is MainViewModel vm && sender is ComboBox comboBox && comboBox.DataContext is SearchResult result)
vm.LoadVersionsCommand.Execute(result);
}
private void OpenHyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
if (e.Uri is null)
return;
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri) { UseShellExecute = true });
e.Handled = true;
}
}
@@ -0,0 +1,164 @@
<UserControl x:Class="ArduManager.Views.PlatformsView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<UserControl.Resources>
<Style x:Key="PlatformCardBorderStyle" TargetType="Border">
<Setter Property="Background" Value="White" />
<Setter Property="BorderBrush" Value="#DDDDDD" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="8" />
<Setter Property="Padding" Value="6" />
<Setter Property="Margin" Value="0,0,0,4" />
</Style>
<Style TargetType="Button">
<Setter Property="Height" Value="30" />
<Setter Property="Padding" Value="12,0" />
<Setter Property="MinWidth" Value="92" />
<Setter Property="Margin" Value="6,0,0,0" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<Style TargetType="TextBox">
<Setter Property="Height" Value="30" />
<Setter Property="Padding" Value="8,0" />
<Setter Property="VerticalContentAlignment" Value="Center" />
</Style>
<Style TargetType="ComboBox">
<Setter Property="Height" Value="30" />
<Setter Property="Width" Value="105" />
<Setter Property="Padding" Value="5,0" />
<Setter Property="Margin" Value="6,0,0,0" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</UserControl.Resources>
<Grid Margin="8" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid Grid.Row="0" Margin="0,0,0,10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
<TextBox x:Name="PackageUrlTextBox"
Text="{Binding NewPackageUrl, UpdateSourceTrigger=PropertyChanged}"
ToolTip="Ссылка на package_*_index.json"
FontSize="14" />
<TextBlock Text="Ссылка для менеджера плат"
Foreground="#9CA3AF"
FontSize="14"
Margin="9,0,0,0"
VerticalAlignment="Center"
IsHitTestVisible="False">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding Text, ElementName=PackageUrlTextBox}" Value="">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Grid>
<ComboBox Grid.Column="1"
Width="98"
ItemsSource="{Binding StandardPlatforms}"
SelectedItem="{Binding SelectedStandardPlatform, Mode=TwoWay}"
DisplayMemberPath="Name"
ToolTip="Стандартные ссылки на платформы" />
<Button Grid.Column="2" Content="Добавить" Width="86" Command="{Binding AddUrlCommand}" />
<Button Grid.Column="3" Content="Обновить" Width="86" Command="{Binding ReloadCommand}" />
</Grid>
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto">
<ItemsControl ItemsSource="{Binding Platforms}" Margin="0,0,14,0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Style="{StaticResource PlatformCardBorderStyle}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0"
Orientation="Vertical"
VerticalAlignment="Center"
Margin="0,0,8,0">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Title}"
FontSize="15"
FontWeight="SemiBold"
VerticalAlignment="Center"
TextTrimming="CharacterEllipsis" />
<TextBlock Text="{Binding VersionBadge}"
FontSize="13"
FontWeight="Normal"
Foreground="#4B5563"
Margin="6,1,0,0"
VerticalAlignment="Center"
TextTrimming="CharacterEllipsis" />
</StackPanel>
<TextBlock FontSize="11"
Foreground="#666"
Margin="0,1,0,0"
Visibility="{Binding HasGitHubUrl, Converter={StaticResource BoolToVisibility}}"
TextTrimming="CharacterEllipsis">
<Hyperlink NavigateUri="{Binding GitHubUrl}"
RequestNavigate="OpenHyperlink_RequestNavigate">
<Run Text="{Binding GitHubLinkText, Mode=OneWay}" />
</Hyperlink>
</TextBlock>
</StackPanel>
<ComboBox Grid.Column="1"
ItemsSource="{Binding Versions}"
SelectedItem="{Binding SelectedVersion, Mode=TwoWay}" />
<Button Grid.Column="2"
Content="Установить"
Command="{Binding InstallCommand}" />
<Button Grid.Column="3"
Content="Удалить"
Command="{Binding RemoveCommand}" />
<ProgressBar Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="4"
Height="7" Minimum="0" Maximum="100"
Value="{Binding ProgressValue}"
Visibility="{Binding IsBusy, Converter={StaticResource BoolToVisibility}}"
Margin="0,6,0,0" />
<TextBlock Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="4"
Text="{Binding Status}"
Visibility="{Binding HasStatus, Converter={StaticResource BoolToVisibility}}"
Foreground="#4B5563"
FontSize="12"
Margin="0,4,0,0"
TextWrapping="Wrap" />
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
</UserControl>
@@ -0,0 +1,121 @@
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using ArduboardsManager.App.Services;
using AppMainViewModel = ArduManager.ViewModels.MainViewModel;
using BoardsMainViewModel = ArduboardsManager.App.ViewModels.MainViewModel;
namespace ArduManager.Views;
public partial class PlatformsView : UserControl
{
private readonly BoardsMainViewModel _viewModel;
private bool _initialized;
private bool _isStatusActive;
public string CurrentStatus => _viewModel.FooterText;
public bool CurrentIsBusy => _viewModel.IsLoading;
public bool IsStatusActive
{
get => _isStatusActive;
set
{
_isStatusActive = value;
if (value)
PushStatusToHost();
}
}
public PlatformsView()
{
InitializeComponent();
_viewModel = new BoardsMainViewModel();
_viewModel.StatusChanged += OnBoardsStatusChanged;
_viewModel.BusyChanged += OnBoardsBusyChanged;
_viewModel.LogMessage += OnBoardsLogMessage;
DataContext = _viewModel;
Loaded += async (_, _) => await InitializeSafelyAsync();
}
private AppMainViewModel? TryGetHostViewModel()
{
return Window.GetWindow(this)?.DataContext as AppMainViewModel;
}
private void PushStatusToHost()
{
if (!IsStatusActive)
return;
TryGetHostViewModel()?.SetPlatformStatus(_viewModel.FooterText, _viewModel.IsLoading);
}
private void OnBoardsStatusChanged(string message)
{
Dispatcher.Invoke(() =>
{
if (IsStatusActive)
TryGetHostViewModel()?.SetPlatformStatus(message, _viewModel.IsLoading);
});
}
private void OnBoardsBusyChanged(bool isBusy)
{
Dispatcher.Invoke(() =>
{
if (IsStatusActive)
TryGetHostViewModel()?.SetPlatformStatus(_viewModel.FooterText, isBusy);
});
}
private void OnBoardsLogMessage(string message)
{
Dispatcher.Invoke(() => TryGetHostViewModel()?.AddPlatformLog(message));
}
private void OpenHyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
try
{
if (e.Uri is not null)
{
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri)
{
UseShellExecute = true
});
e.Handled = true;
}
}
catch (Exception ex)
{
LogService.Error("Failed to open hyperlink", ex);
MessageBox.Show(ex.Message, "Не удалось открыть ссылку", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private async Task InitializeSafelyAsync()
{
if (_initialized)
return;
_initialized = true;
try
{
await _viewModel.InitializeAsync();
PushStatusToHost();
}
catch (Exception ex)
{
LogService.Error("Boards initialization failed", ex);
MessageBox.Show(
$"Ошибка при запуске вкладки платформ. Подробности записаны в лог:\n{AppPaths.CurrentLogFile}\n\n{ex.Message}",
"ArduManager",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
}
@@ -0,0 +1,13 @@
{
"ESP8266": "https://arduino.esp8266.com/stable/package_esp8266com_index.json",
"ESP32": "https://espressif.github.io/arduino-esp32/package_esp32_index.json",
"RP2040/RP2350": "https://github.com/earlephilhower/arduino-pico/releases/download/global/package_rp2040_index.json",
"STM32duino": "https://github.com/stm32duino/BoardManagerFiles/raw/main/package_stmicroelectronics_index.json",
"Arduino official": "https://downloads.arduino.cc/packages/package_index.json",
"MicroCore": "https://mcudude.github.io/MicroCore/package_MCUdude_MicroCore_index.json",
"ATTinyCore": "http://drazzy.com/package_drazzy.com_index.json",
"MiniCore": "https://mcudude.github.io/MiniCore/package_MCUdude_MiniCore_index.json",
"MightyCore": "https://mcudude.github.io/MightyCore/package_MCUdude_MightyCore_index.json",
"MegaCore": "https://mcudude.github.io/MegaCore/package_MCUdude_MegaCore_index.json",
"LGT8fx": "https://raw.githubusercontent.com/dbuezas/lgt8fx/master/package_lgt8fx_index.json"
}
@@ -1,51 +0,0 @@
using ArdulibsManager.Infrastructure;
namespace ArdulibsManager.Models;
public sealed class InstalledLibrary : ObservableObject
{
private string? _latestVersion;
private bool _isChecking;
private bool _hasUpdate;
private string? _status;
private string? _updateRepositoryFullName;
public required string Name { get; init; }
public string? Version { get; init; }
public string? PropertiesVersion { get; init; }
public string? InstalledRef { get; init; }
public string? Maintainer { get; init; }
public string? Url { get; init; }
public required string LocalPath { get; init; }
public string? RepositoryFullName { get; init; }
public string? UpdateRepositoryFullName
{
get => _updateRepositoryFullName;
set => SetProperty(ref _updateRepositoryFullName, value);
}
public string? LatestVersion
{
get => _latestVersion;
set => SetProperty(ref _latestVersion, value);
}
public bool HasUpdate
{
get => _hasUpdate;
set => SetProperty(ref _hasUpdate, value);
}
public bool IsChecking
{
get => _isChecking;
set => SetProperty(ref _isChecking, value);
}
public string? Status
{
get => _status;
set => SetProperty(ref _status, value);
}
}
@@ -1,155 +0,0 @@
<Window x:Class="ArdulibsManager.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:ArdulibsManager.ViewModels"
mc:Ignorable="d"
Title="Arduino GitHub Library Manager" Height="520" Width="700"
WindowStartupLocation="CenterScreen"
Loaded="Window_Loaded">
<Window.DataContext>
<vm:MainViewModel />
</Window.DataContext>
<Window.InputBindings>
<KeyBinding Key="F5" Command="{Binding RescanCommand}" />
</Window.InputBindings>
<DockPanel>
<Border DockPanel.Dock="Bottom" Background="#F5F5F5" BorderBrush="#DDD" BorderThickness="1,1,0,0" Padding="10">
<DockPanel>
<TextBlock Text="{Binding Status}" VerticalAlignment="Center" />
<ProgressBar DockPanel.Dock="Right" Width="160" Height="14" IsIndeterminate="{Binding IsBusy}" Margin="12,0,0,0" />
</DockPanel>
</Border>
<TabControl Margin="10">
<TabItem Header="Поиск">
<Grid Margin="8">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Margin="0,0,0,8">
<TextBox FontSize="16" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}" ToolTip="Минимум 3 символа" />
</StackPanel>
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto">
<ItemsControl ItemsSource="{Binding SearchResults}" Margin="0,0,8,0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="#DDDDDD" BorderThickness="1" CornerRadius="8" Padding="6" Margin="0,0,0,4" Background="White">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel>
<TextBlock Text="{Binding Title}" FontSize="14" FontWeight="SemiBold" />
<TextBlock Text="{Binding Url}" Foreground="#666" Margin="0,0,0,1" FontSize="11" />
<TextBlock Text="{Binding InstalledLibrary.Version, StringFormat=Установлена версия {0}}" FontSize="11" />
<TextBlock Text="{Binding Status}" Foreground="#A45" FontSize="12" />
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center">
<ComboBox Width="84" MinWidth="84" Margin="8,0,0,0"
ItemsSource="{Binding Tags}"
SelectedItem="{Binding SelectedTag}"
DisplayMemberPath="DisplayName"
DropDownOpened="VersionComboBox_DropDownOpened"
MaxDropDownHeight="220"
IsTextSearchEnabled="False"
ToolTip="Пока версия не выбрана, установка берёт latest GitHub tag" />
<Button Content="{Binding InstallButtonText}" Command="{Binding DataContext.InstallCommand, RelativeSource={RelativeSource AncestorType=Window}}" CommandParameter="{Binding}" />
</StackPanel>
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
</TabItem>
<TabItem Header="Установленные">
<Grid Margin="8">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Margin="0,0,0,8">
<Button Content="Обновить список" Width="150" Height="30" Command="{Binding RescanCommand}" />
<Button Content="Обновить библиотеки" Width="150" Height="30" Margin="8,0,0,0" Command="{Binding UpdateAllCommand}" />
</StackPanel>
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto">
<ItemsControl ItemsSource="{Binding InstalledLibraries}" Margin="0,0,8,0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="#DDDDDD" BorderThickness="1" CornerRadius="8" Padding="6" Margin="0,0,0,4" Background="White">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock Text="{Binding Name}" FontSize="14" FontWeight="SemiBold" TextTrimming="CharacterEllipsis" MaxWidth="270" />
<TextBlock Text="{Binding Version, StringFormat= v{0}}" FontSize="14" Margin="8,0,0,0" Foreground="#555" />
<TextBlock Text=" • есть обновление" FontSize="12" Margin="8,2,0,0" Foreground="#A45">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding HasUpdate}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center" Margin="12,0,0,0">
<Button Content="Обновить" Width="79" Height="30" Margin="0,0,4,0" ToolTip="Установить свежую версию" Command="{Binding DataContext.UpdateCommand, RelativeSource={RelativeSource AncestorType=Window}}" CommandParameter="{Binding}" />
<Button Content="Открыть" Width="75" Height="30" Margin="0,0,4,0" ToolTip="Открыть папку библиотеки" Command="{Binding DataContext.OpenFolderCommand, RelativeSource={RelativeSource AncestorType=Window}}" CommandParameter="{Binding}" />
<Button Content="Удалить" Width="75" Height="30" Margin="0,0,0,0" ToolTip="Удалить библиотеку" Command="{Binding DataContext.RemoveCommand, RelativeSource={RelativeSource AncestorType=Window}}" CommandParameter="{Binding}" />
</StackPanel>
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
</TabItem>
<TabItem Header="Настройки">
<StackPanel Margin="12" MaxWidth="760" HorizontalAlignment="Left">
<TextBlock Text="Папка Arduino libraries" FontWeight="SemiBold" />
<DockPanel>
<Button DockPanel.Dock="Right" Content="Выбрать" Width="86" Command="{Binding BrowseLibrariesCommand}" />
<Button DockPanel.Dock="Right" Content="Открыть" Width="86" Command="{Binding OpenFolderCommand}" Margin="4,0,4,0" />
<TextBox Text="{Binding LibrariesPath, UpdateSourceTrigger=PropertyChanged}" />
</DockPanel>
<TextBlock Text="Список репозиториев" FontWeight="SemiBold" Margin="4,16,4,0" />
<DockPanel>
<Button DockPanel.Dock="Right" Content="Обновить" Width="86" Command="{Binding RefreshRegistryCommand}" />
<TextBox Text="{Binding RepositoryListUrl, UpdateSourceTrigger=PropertyChanged}" />
</DockPanel>
<TextBlock Text="GitHub token (опционально, для повышения лимитов)" FontWeight="SemiBold" Margin="4,16,4,0" />
<TextBox Text="{Binding GitHubToken, UpdateSourceTrigger=PropertyChanged}" Margin="0,0,0,12" />
<CheckBox Content="Проверять обновления при запуске" IsChecked="{Binding CheckUpdatesOnStartup}" Margin="4,0,4,12" />
<Button Content="Сохранить настройки" Width="180" HorizontalAlignment="Left" Command="{Binding SaveSettingsCommand}" />
</StackPanel>
</TabItem>
<TabItem Header="Лог">
<ListBox ItemsSource="{Binding Logs}" Margin="8" FontFamily="Consolas" />
</TabItem>
</TabControl>
</DockPanel>
</Window>
@@ -1,26 +0,0 @@
using System.Windows;
using System.Windows.Controls;
using ArdulibsManager.Models;
using ArdulibsManager.ViewModels;
namespace ArdulibsManager.Views;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (DataContext is MainViewModel vm)
vm.InitializeCommand.Execute(null);
}
private void VersionComboBox_DropDownOpened(object sender, EventArgs e)
{
if (DataContext is MainViewModel vm && sender is ComboBox comboBox && comboBox.DataContext is SearchResult result)
vm.LoadVersionsCommand.Execute(result);
}
}