- BepInEx Installation schneller gemach

- BepInEx Installation Progress Bar hinzugefügt um fortschritt anzuzeigen
-BepInEx Leere ordner werden jetzt direkt mit erstellt, falls der user selber prüfen will oder so damit er sie sieht. Also 1zu1 die ZIP
-Mods werden jetzt vom ftp server gelesen mit version und config suche. Plugin funktion fehlt dafür nur
- Text Editor für Config von Simple zu wirklichen Editor mit highlights wie notepad++ geändert. funktioniert aber noch nicht
This commit is contained in:
tbS
2025-08-27 19:19:23 +02:00
parent 2c7d442441
commit cf6bd3765f
9 changed files with 497 additions and 60 deletions

View File

@@ -20,5 +20,23 @@
<Application.Styles> <Application.Styles>
<FluentTheme/> <FluentTheme/>
<StyleInclude Source="Styles.axaml"/> <StyleInclude Source="Styles.axaml"/>
<Style>
<Style.Resources>
<SolidColorBrush x:Key="Cfg.SectionBrush" Color="#C586C0"/>
<!-- violett -->
<SolidColorBrush x:Key="Cfg.CommentBrush" Color="#6A9955"/>
<!-- grün -->
<SolidColorBrush x:Key="Cfg.KeyBrush" Color="#4FC1FF"/>
<!-- blau -->
<SolidColorBrush x:Key="Cfg.EqualBrush" Color="#F44747"/>
<!-- rot -->
<SolidColorBrush x:Key="Cfg.ValueBrush" Color="#D4D4D4"/>
<!-- hellgrau -->
<SolidColorBrush x:Key="Cfg.NumberBrush" Color="#CE9178"/>
<!-- amber/zahl -->
<SolidColorBrush x:Key="Cfg.BgBrush" Color="#1E1E1E"/>
<SolidColorBrush x:Key="Cfg.FgBrush" Color="#D4D4D4"/>
</Style.Resources>
</Style>
</Application.Styles> </Application.Styles>
</Application> </Application>

View File

@@ -1,8 +1,15 @@
using Avalonia; using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml; using Avalonia.Markup.Xaml;
using Avalonia.Media;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Valheim_Dashboard.ViewModels; using Valheim_Dashboard.ViewModels;
using Valheim_Dashboard.Views; using Valheim_Dashboard.Views;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Highlighting.Xshd;
using System;
namespace Valheim_Dashboard; namespace Valheim_Dashboard;
@@ -13,8 +20,90 @@ public partial class App : Application
AvaloniaXamlLoader.Load(this); AvaloniaXamlLoader.Load(this);
} }
private void RegisterCfgHighlighting()
{
static HighlightingBrush HB(string key)
{
var obj = Application.Current!.FindResource(key);
if (obj is ISolidColorBrush scb)
return new SimpleHighlightingBrush(scb.Color); // <-- Color, nicht IBrush
throw new InvalidOperationException($"Resource '{key}' must be a SolidColorBrush.");
}
var section = new HighlightingColor { Foreground = HB("Cfg.SectionBrush"), FontWeight = FontWeight.Bold };
var comment = new HighlightingColor { Foreground = HB("Cfg.CommentBrush"), FontStyle = FontStyle.Italic };
var key = new HighlightingColor { Foreground = HB("Cfg.KeyBrush") };
var equal = new HighlightingColor { Foreground = HB("Cfg.EqualBrush") };
var value = new HighlightingColor { Foreground = HB("Cfg.ValueBrush") };
var number = new HighlightingColor { Foreground = HB("Cfg.NumberBrush") };
var rules = new HighlightingRuleSet();
// 1) Kommentare: ^\s*#.*
rules.Rules.Add(new HighlightingRule
{
Regex = new Regex(@"^\s*#.*", RegexOptions.Compiled | RegexOptions.Multiline),
Color = comment
});
// 2) Sektionen: [Name]
rules.Rules.Add(new HighlightingRule
{
Regex = new Regex(@"^\s*\[[^\]\r\n]+\]\s*$", RegexOptions.Compiled | RegexOptions.Multiline),
Color = section
});
// 3a) Schl<68>ssel (von Zeilenbeginn bis vor "=")
rules.Spans.Add(new HighlightingSpan
{
StartExpression = new Regex(@"^\s*", RegexOptions.Compiled | RegexOptions.Multiline),
EndExpression = new Regex(@"=", RegexOptions.Compiled),
SpanColor = key
});
// 3b) Gleichheitszeichen
rules.Rules.Add(new HighlightingRule
{
Regex = new Regex(@"=", RegexOptions.Compiled),
Color = equal
});
// 3c) Werte (von "=" bis Zeilenende; Kommentar nicht einschlie<69>en)
rules.Spans.Add(new HighlightingSpan
{
StartExpression = new Regex(@"=(?!.*#)", RegexOptions.Compiled), // bis Zeilenende ohne #
EndExpression = new Regex(@"$", RegexOptions.Compiled | RegexOptions.Multiline),
SpanColor = value
});
// 3d) Zahlen im Wert hervorheben
rules.Rules.Add(new HighlightingRule
{
Regex = new Regex(@"\b-?\d+(\.\d+)?\b", RegexOptions.Compiled),
Color = number
});
var def = new CustomHighlightingDefinition("CfgDark", rules);
HighlightingManager.Instance.RegisterHighlighting("CfgDark", new[] { ".cfg", ".cfg.txt", ".properties" }, def);
IBrush? TryRes(string key) => (IBrush?)Current?.FindResource(key);
}
// kleine Helper-Definition
sealed class CustomHighlightingDefinition : IHighlightingDefinition
{
public CustomHighlightingDefinition(string name, HighlightingRuleSet rules) { Name = name; MainRuleSet = rules; }
public string Name { get; }
public HighlightingRuleSet MainRuleSet { get; }
public IEnumerable<HighlightingColor> NamedHighlightingColors => Array.Empty<HighlightingColor>();
public IDictionary<string, string> Properties => new Dictionary<string, string>();
public HighlightingRuleSet? GetNamedRuleSet(string name) => null;
public HighlightingColor? GetNamedColor(string name) => null;
}
public override void OnFrameworkInitializationCompleted() public override void OnFrameworkInitializationCompleted()
{ {
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{ {
// ViewModelLocator im Ressourcenverzeichnis registrieren // ViewModelLocator im Ressourcenverzeichnis registrieren
@@ -25,7 +114,7 @@ public partial class App : Application
DataContext = (Resources["Locator"] as ViewModelLocator)?.MainWindowViewModel, DataContext = (Resources["Locator"] as ViewModelLocator)?.MainWindowViewModel,
}; };
} }
RegisterCfgHighlighting();
base.OnFrameworkInitializationCompleted(); base.OnFrameworkInitializationCompleted();
} }
} }

View File

@@ -252,7 +252,9 @@ namespace Valheim_Dashboard
request.UseBinary = true; request.UseBinary = true;
request.UsePassive = true; request.UsePassive = true;
request.KeepAlive = false; request.KeepAlive = false;
Debug.WriteLine($"FTP URI: {uri}");
return request; return request;
} }
public async Task<List<FtpItem>> OpenFolderAsync(string folderPath) public async Task<List<FtpItem>> OpenFolderAsync(string folderPath)

View File

@@ -14,6 +14,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Avalonia" Version="11.2.3" /> <PackageReference Include="Avalonia" Version="11.2.3" />
<PackageReference Include="Avalonia.AvaloniaEdit" Version="11.3.0" />
<PackageReference Include="Avalonia.Desktop" Version="11.2.3" /> <PackageReference Include="Avalonia.Desktop" Version="11.2.3" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.2.3" /> <PackageReference Include="Avalonia.Themes.Fluent" Version="11.2.3" />
<PackageReference Include="Avalonia.Fonts.Inter" Version="11.2.3" /> <PackageReference Include="Avalonia.Fonts.Inter" Version="11.2.3" />

View File

@@ -1,6 +1,8 @@
using Avalonia.Controls; using Avalonia.Controls;
using AvaloniaEdit.Document;
using ReactiveUI; using ReactiveUI;
using System; using System;
using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
@@ -10,6 +12,8 @@ using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Reactive; using System.Reactive;
using System.Reactive.Linq; using System.Reactive.Linq;
using System.Reflection;
using System.Text;
using System.Text.Json; using System.Text.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
using Valheim_Dashboard.Models; using Valheim_Dashboard.Models;
@@ -74,11 +78,19 @@ public class ServerDashboardViewModel : ViewModelBase
} }
private string _selectedModConfig; public TextDocument ConfigDocument { get; } = new TextDocument();
public string SelectedModConfig
private string? _selectedModConfig;
public string? SelectedModConfig
{ {
get => _selectedModConfig; get => _selectedModConfig;
set => this.RaiseAndSetIfChanged(ref _selectedModConfig, value); set
{
this.RaiseAndSetIfChanged(ref _selectedModConfig, value);
var text = value ?? string.Empty;
if (ConfigDocument.Text != text)
ConfigDocument.Text = text;
}
} }
private Window _mainWindow; private Window _mainWindow;
public void SetMainWindow(Window mainWindow) public void SetMainWindow(Window mainWindow)
@@ -111,13 +123,18 @@ public class ServerDashboardViewModel : ViewModelBase
SaveConfigCommand = ReactiveCommand.Create(SaveConfig); SaveConfigCommand = ReactiveCommand.Create(SaveConfig);
RemoveModCommand = ReactiveCommand.Create(RemoveMod); RemoveModCommand = ReactiveCommand.Create(RemoveMod);
// DEBUG: harter Testtext – MUSS im Editor erscheinen
ConfigDocument.Text = "[Berries]\n# test\nRaspberryCost = 5";
// Demo // Demo
//BepInExStatus = "Nicht installiert"; //BepInExStatus = "Nicht installiert";
//ShowInstallButton = true; //ShowInstallButton = true;
//ShowUpdateButton = false; //ShowUpdateButton = false;
Mods.Add(new ModInfo { Name = "ValheimPlus", Version = "1.0.0", ConfigPath = "config/valheim_plus.cfg" }); //Mods.Add(new ModInfo { Name = "ValheimPlus", Version = "1.0.0", ConfigPath = "config/valheim_plus.cfg" });
Mods.Add(new ModInfo { Name = "BetterUI", Version = "2.3.4", ConfigPath = "config/better_ui.cfg" }); //Mods.Add(new ModInfo { Name = "BetterUI", Version = "2.3.4", ConfigPath = "config/better_ui.cfg" });
// Start async Initialisierung // Start async Initialisierung
_ = InitializeAsync(); _ = InitializeAsync();
@@ -130,6 +147,7 @@ public class ServerDashboardViewModel : ViewModelBase
IsLoading = true; IsLoading = true;
await CheckBepInExStatus(); await CheckBepInExStatus();
IsLoading = false; IsLoading = false;
await LoadModsFromServer();
} }
private async Task CheckBepInExStatus() private async Task CheckBepInExStatus()
@@ -147,12 +165,6 @@ public class ServerDashboardViewModel : ViewModelBase
return; return;
} }
var llist = await FtpViewModel._ftpClient.ListDirectoryDetailsAsync(FtpViewModel._currentPath+ "/BepInEx/core");
foreach (var item1 in llist)
{
Debug.WriteLine(item1.Name);
}
// BepInEx installiert, jetzt Version prüfen // BepInEx installiert, jetzt Version prüfen
string remoteDllPath = FtpViewModel._currentPath + "/BepInEx/core/BepInEx.dll"; string remoteDllPath = FtpViewModel._currentPath + "/BepInEx/core/BepInEx.dll";
Debug.WriteLine("remotedllpath: " + remoteDllPath); Debug.WriteLine("remotedllpath: " + remoteDllPath);
@@ -207,52 +219,51 @@ public class ServerDashboardViewModel : ViewModelBase
/* private void InstallBepInEx()
{
BepInExStatus = "Installiert (vX.Y.Z)";
ShowInstallButton = false;
ShowUpdateButton = true;
}
*/
private readonly HttpClient _http = new HttpClient(); private readonly HttpClient _http = new HttpClient();
private int _progressValue;
public int ProgressValue
{
get => _progressValue;
set => this.RaiseAndSetIfChanged(ref _progressValue, value);
}
private string _progressText;
public string ProgressText
{
get => _progressText;
set => this.RaiseAndSetIfChanged(ref _progressText, value);
}
private bool _isProgress;
public bool IsProgress
{
get => _isProgress;
set => this.RaiseAndSetIfChanged(ref _isProgress, value);
}
public async Task InstallBepInEx() public async Task InstallBepInEx()
{ {
Debug.WriteLine("Install star"); Debug.WriteLine("Install start");
ShowInstallButton = false;
IsProgress = true;
ProgressValue = 0;
ProgressText = "Starte…";
try try
{ {
_http.DefaultRequestHeaders.UserAgent.Clear(); _http.DefaultRequestHeaders.UserAgent.Clear();
_http.DefaultRequestHeaders.UserAgent.ParseAdd("ValheimDashboard/1.0.0"); _http.DefaultRequestHeaders.UserAgent.ParseAdd("ValheimDashboard/1.0.0");
HttpResponseMessage resp; // 1) Thunderstore API
try HttpResponseMessage resp = await _http.GetAsync("https://thunderstore.io/api/experimental/package/denikson/BepInExPack_Valheim/");
{ resp.EnsureSuccessStatusCode();
resp = await _http.GetAsync("https://thunderstore.io/api/experimental/package/denikson/BepInExPack_Valheim/");
resp.EnsureSuccessStatusCode();
}
catch (WebException ex)
{
Debug.WriteLine($"Fehler bei Thunderstore Request: {ex.Message}");
return;
}
using var stream = await resp.Content.ReadAsStreamAsync(); using var stream = await resp.Content.ReadAsStreamAsync();
JsonDocument doc; using var doc = await JsonDocument.ParseAsync(stream);
try
{
doc = await JsonDocument.ParseAsync(stream);
}
catch (Exception ex)
{
Debug.WriteLine($"Fehler beim Parsen von JSON: {ex.Message}");
return;
}
if (!doc.RootElement.TryGetProperty("latest", out var latestElement) || if (!doc.RootElement.TryGetProperty("latest", out var latest) ||
!latestElement.TryGetProperty("download_url", out var urlElement)) !latest.TryGetProperty("download_url", out var urlElement))
{ {
Debug.WriteLine("download_url nicht gefunden im JSON"); Debug.WriteLine("download_url nicht gefunden im JSON");
return; return;
@@ -261,13 +272,16 @@ public class ServerDashboardViewModel : ViewModelBase
string downloadUrl = urlElement.GetString()!; string downloadUrl = urlElement.GetString()!;
Debug.WriteLine($"Starte Download von BepInExPack: {downloadUrl}"); Debug.WriteLine($"Starte Download von BepInExPack: {downloadUrl}");
// --- Fortschritt: Download = 0..25 %
const int DL_START = 0, DL_END = 25, MKDIR_END = 40, UP_END = 100;
using var downloadResponse = await _http.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead); using var downloadResponse = await _http.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead);
downloadResponse.EnsureSuccessStatusCode(); downloadResponse.EnsureSuccessStatusCode();
var totalBytes = downloadResponse.Content.Headers.ContentLength ?? -1L; var totalBytes = downloadResponse.Content.Headers.ContentLength ?? -1L;
using var downloadStream = await downloadResponse.Content.ReadAsStreamAsync(); using var downloadStream = await downloadResponse.Content.ReadAsStreamAsync();
using var ms = new MemoryStream(); using var ms = new MemoryStream();
byte[] buffer = new byte[8192]; byte[] buffer = new byte[64 * 1024]; // größerer Buffer = schneller
long totalRead = 0; long totalRead = 0;
int bytesRead; int bytesRead;
while ((bytesRead = await downloadStream.ReadAsync(buffer, 0, buffer.Length)) > 0) while ((bytesRead = await downloadStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
@@ -277,22 +291,85 @@ public class ServerDashboardViewModel : ViewModelBase
if (totalBytes > 0) if (totalBytes > 0)
{ {
int progress = (int)((totalRead * 100) / totalBytes); int dlPct = (int)((totalRead * 100) / totalBytes);
Console.Write($"\rDownload Fortschritt: {progress}%"); int uiPct = DL_START + (int)((dlPct / 100.0) * (DL_END - DL_START));
ProgressValue = uiPct;
ProgressText = $"Download: {dlPct}%";
} }
} }
ms.Position = 0; ms.Position = 0;
Console.WriteLine("\nDownload abgeschlossen, entpacke ZIP..."); ProgressValue = DL_END;
ProgressText = "Download fertig. Entpacke…";
// 2) ZIP öffnen
using var archive = new ZipArchive(ms); using var archive = new ZipArchive(ms);
// 2a) Alle Ordner (inkl. leerer) sammeln -> erster Ordnerteil (BepInExPack_Valheim) wird weggeschnitten
var allFolders = new HashSet<string>(StringComparer.Ordinal);
var allFiles = new List<ZipArchiveEntry>();
foreach (var entry in archive.Entries) foreach (var entry in archive.Entries)
{ {
if (string.IsNullOrEmpty(entry.Name)) continue;
var parts = entry.FullName.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries); var parts = entry.FullName.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length <= 1) continue; if (parts.Length <= 1) continue; // root-pack-ordner allein ignorieren
string relativePath = string.Join('/', parts.Skip(1));
// relative Teile ohne Top-Level-Ordner
var relParts = parts.Skip(1).ToArray();
if (string.IsNullOrEmpty(entry.Name))
{
// Ein echter Verzeichniseintrag im ZIP (leer)
string folder = string.Join('/', relParts);
if (!string.IsNullOrWhiteSpace(folder))
allFolders.Add(folder);
}
else
{
// Datei -> über alle Zwischenordner iterieren
for (int i = 0; i < relParts.Length - 1; i++)
{
string folder = string.Join('/', relParts.Take(i + 1));
allFolders.Add(folder);
}
allFiles.Add(entry);
}
}
// --- Fortschritt: Ordner anlegen = 25..40 %
ProgressText = "Lege Ordner an…";
int foldersTotal = allFolders.Count;
int foldersDone = 0;
foreach (var folder in allFolders.OrderBy(s => s.Length)) // erst flache, dann tiefe Ordner
{
Debug.WriteLine("ordner: " + folder);
try
{
// relative Pfade an Ensure übergeben – deine CreateFtpWebRequest() hängt _currentPath selbst an
await FtpViewModel._ftpClient.EnsureFtpDirectoryExistsAsync(
FtpViewModel._currentPath.TrimEnd('/') + "/" + folder
);
}
catch (Exception ex)
{
Debug.WriteLine($"Ordner konnte nicht erstellt werden: {folder} - {ex.Message}");
// idempotent – wenn schon vorhanden, passts
}
foldersDone++;
int uiPct = DL_END + (int)(((foldersDone / (double)Math.Max(1, foldersTotal)) * (MKDIR_END - DL_END)));
ProgressValue = uiPct;
ProgressText = $"Ordner: {foldersDone}/{foldersTotal}";
}
// --- Fortschritt: Dateien hochladen = 40..100 %
ProgressText = "Lade Dateien hoch…";
int filesTotal = allFiles.Count;
int filesDone = 0;
foreach (var entry in allFiles)
{
var parts = entry.FullName.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
var relativePath = string.Join('/', parts.Skip(1)); // Top-Level-Ordner weg
string remotePath = FtpViewModel._currentPath.TrimEnd('/') + "/" + relativePath; string remotePath = FtpViewModel._currentPath.TrimEnd('/') + "/" + relativePath;
try try
@@ -304,25 +381,243 @@ public class ServerDashboardViewModel : ViewModelBase
{ {
Debug.WriteLine($"FTP Upload Fehler für {remotePath}: {ex.Message}"); Debug.WriteLine($"FTP Upload Fehler für {remotePath}: {ex.Message}");
} }
filesDone++;
int uiPct = MKDIR_END + (int)(((filesDone / (double)Math.Max(1, filesTotal)) * (UP_END - MKDIR_END)));
ProgressValue = uiPct;
ProgressText = $"Hochgeladen: {filesDone}/{filesTotal}";
} }
ProgressValue = 100;
ProgressText = "Fertig ✅";
await CheckBepInExStatus(); await CheckBepInExStatus();
} }
catch (Exception ex) catch (Exception ex)
{ {
Debug.WriteLine($"Unbekannter Fehler: {ex}"); Debug.WriteLine($"Unbekannter Fehler: {ex}");
ProgressText = "Fehler";
}
finally
{
IsProgress = false;
} }
} }
private void UpdateBepInEx() private void UpdateBepInEx()
{ {
BepInExStatus = "Aktuell (vX.Y.Z)"; BepInExStatus = "Aktuell (vX.Y.Z)";
ShowUpdateButton = false; ShowUpdateButton = false;
} }
//Mod Liste holen
// Hilfsfunktionen
static string NormalizeKey(string s)
{
// nur Buchstaben/Ziffern, alles klein
var sb = new StringBuilder(s.Length);
foreach (var ch in s)
if (char.IsLetterOrDigit(ch))
sb.Append(char.ToLowerInvariant(ch));
return sb.ToString();
}
static string[] SplitBySeparators(string s)
{
// trennt per _,.,-,+, Leerzeichen und Slash/Backslash
return s.Split(new[] { '_', '.', '-', '+', ' ', '/', '\\' },
StringSplitOptions.RemoveEmptyEntries);
}
static string ExtractCoreModName(string dllNameNoExt)
{
var parts = SplitBySeparators(dllNameNoExt);
if (parts.Length == 0) return dllNameNoExt;
// häufig ist der letzte Part der eigentliche Modname
return parts[^1];
}
static IEnumerable<string> BuildCandidates(string dllNameNoExt)
{
var parts = SplitBySeparators(dllNameNoExt);
// 1) ganzer Name
yield return dllNameNoExt;
// 2) Core-Name (letzter Part)
if (parts.Length > 0)
yield return parts[^1];
// 3) Varianten mit Punkt/Unterstrich (für Fälle wie Advize_PlantEverything vs advize.PlantEverything)
if (parts.Length > 1)
{
yield return string.Join(".", parts);
yield return string.Join("_", parts);
}
}
static int LongestCommonSubsequenceLen(string a, string b)
{
// kleine, schnelle Heuristik als Fallback (O(n*m)), nur bei wenigen Kandidaten benutzt
var dp = new int[a.Length + 1, b.Length + 1];
for (int i = 1; i <= a.Length; i++)
for (int j = 1; j <= b.Length; j++)
dp[i, j] = a[i - 1] == b[j - 1] ? dp[i - 1, j - 1] + 1 : Math.Max(dp[i - 1, j], dp[i, j - 1]);
return dp[a.Length, b.Length];
}
private static string CombineFtp(params string[] parts)
{
return string.Join("/", parts.Where(p => !string.IsNullOrWhiteSpace(p))
.Select(p => p.Trim('/')));
}
private static bool LooksLikeDirectory(dynamic item) // FtpItem? Falls es IsDirectory gibt, nutzen wir das
{
try { return item.IsDirectory; } catch { /* fallback */ }
// Fallback-Heuristik: wenn kein Punkt im Namen, ist es sehr wahrscheinlich ein Ordner
var name = (string)item.Name;
return !name.Contains('.');
}
private async Task<string?> GetDllVersionFromFtpAsync(string remoteDllPath)
{
using var ms = new MemoryStream();
await FtpViewModel._ftpClient.DownloadStreamAsync(remoteDllPath, ms);
ms.Position = 0;
string? version = null;
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".dll");
try
{
await System.IO.File.WriteAllBytesAsync(tempPath, ms.ToArray());
var fvi = FileVersionInfo.GetVersionInfo(tempPath);
version = fvi.FileVersion ?? fvi.ProductVersion;
// Falls FileVersion leer ist, optional Assembly-Version probieren:
if (string.IsNullOrWhiteSpace(version))
{
try
{
var an = AssemblyName.GetAssemblyName(tempPath);
version = an.Version?.ToString();
}
catch { /* ignorieren */ }
}
}
finally
{
try { if (System.IO.File.Exists(tempPath)) System.IO.File.Delete(tempPath); } catch { /* ignore */ }
}
return version;
}
// Hauptmethode
public async Task LoadModsFromServer()
{
try
{
Mods.Clear();
if (ServerSettingsView.method == "ftp")
{
var basePath = FtpViewModel._currentPath.TrimEnd('/');
var pluginsDir = $"{basePath}/BepInEx/plugins";
var configDir = $"{basePath}/BepInEx/config";
var pluginList = await FtpViewModel._ftpClient.ListDirectoryDetailsAsync(pluginsDir);
var configList = await FtpViewModel._ftpClient.ListDirectoryDetailsAsync(configDir);
// Vorbereiten: normalisierte Config-Namen mapen
var cfgFiles = configList
.Where(c => c.Name.EndsWith(".cfg", StringComparison.OrdinalIgnoreCase))
.Select(c => new {
Name = c.Name,
NameNoExt = Path.GetFileNameWithoutExtension(c.Name),
Normalized = NormalizeKey(Path.GetFileNameWithoutExtension(c.Name))
})
.ToList();
foreach (var pl in pluginList)
{
if (!pl.Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
continue;
string dllNoExt = Path.GetFileNameWithoutExtension(pl.Name);
// Kandidaten + normalisierte Kandidaten
var candidates = BuildCandidates(dllNoExt).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
var normCandidates = candidates.Select(NormalizeKey).Distinct().ToList();
// 1) Bevorzugt: Core-Modname muss vorkommen
string core = ExtractCoreModName(dllNoExt);
string normCore = NormalizeKey(core);
// Match: irgendein normalisierter Kandidat kommt im normalisierten Config-Namen vor
var cfgHit = cfgFiles.FirstOrDefault(cf => cf.Normalized.Contains(normCore));
if (cfgHit == null)
{
// 2) sonst: irgendein Kandidat kommt vor
cfgHit = cfgFiles.FirstOrDefault(cf => normCandidates.Any(nc => cf.Normalized.Contains(nc)));
// 3) Fallback: „bester“ Fit über LCS
if (cfgHit == null)
{
cfgHit = cfgFiles
.Select(cf => new {
cf,
score = normCandidates.Max(nc => LongestCommonSubsequenceLen(cf.Normalized, nc))
})
.OrderByDescending(x => x.score)
.FirstOrDefault()?.cf;
}
}
// Version aus DLL ziehen
string dllRemote = $"{pluginsDir}/{pl.Name}";
string? version = null;
try
{
version = await GetDllVersionFromFtpAsync(dllRemote); // wie zuvor implementiert
}
catch (Exception ex)
{
Debug.WriteLine($"Version für {pl.Name} nicht lesbar: {ex.Message}");
}
// Config-Pfad setzen (siehe Punkt 2 unten für „absolute“ URI)
string? configRelPath = cfgHit != null ? $"{FtpViewModel._currentPath}/BepInEx/config/{cfgHit.Name}" : null;
Mods.Add(new ModInfo
{
Name = candidates.Last(), // z.B. „PlantEverything“ statt Autor.Mod
Version = string.IsNullOrWhiteSpace(version) ? "Unbekannt" : version,
ConfigPath = configRelPath // relativ (empfohlen)
});
}
}
else
{
Debug.WriteLine("Plugin funktion fehlt noch");
}
}
catch (Exception ex)
{
Debug.WriteLine($"LoadModsFromFtp Fehler: {ex}");
}
}
//Mod Installation / Löschung //Mod Installation / Löschung
public async Task<string?> OpenFileAsync(Window parent) public async Task<string?> OpenFileAsync(Window parent)

View File

@@ -3,11 +3,12 @@
xmlns:vm="using:Valheim_Dashboard.ViewModels" xmlns:vm="using:Valheim_Dashboard.ViewModels"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="1280" d:DesignHeight="800" mc:Ignorable="d" d:DesignWidth="1424" d:DesignHeight="714"
x:Class="Valheim_Dashboard.Views.MainWindow" x:Class="Valheim_Dashboard.Views.MainWindow"
x:DataType="vm:MainWindowViewModel" CanResize="false" x:DataType="vm:MainWindowViewModel" CanResize="false"
Icon="/Assets/avalonia-logo.ico" Icon="/Assets/avalonia-logo.ico"
Title="Valheim_Dashboard"> Title="Valheim_Dashboard"
>
<Design.DataContext> <Design.DataContext>
<!-- This only sets the DataContext for the previewer in an IDE, <!-- This only sets the DataContext for the previewer in an IDE,

View File

@@ -1,4 +1,5 @@
using Avalonia.Controls; using Avalonia.Controls;
using System.Diagnostics;
using Valheim_Dashboard.ViewModels; using Valheim_Dashboard.ViewModels;
namespace Valheim_Dashboard.Views; namespace Valheim_Dashboard.Views;
@@ -8,6 +9,13 @@ public partial class MainWindow : Window
public MainWindow() public MainWindow()
{ {
InitializeComponent(); InitializeComponent();
// Loggen, sobald das Fenster ge<67>ffnet wurde (Layout fertig)
this.Opened += (_, __) =>
{
Debug.WriteLine($"Window size after open: {Bounds.Width} x {Bounds.Height}");
};
var locator = new ViewModelLocator(); var locator = new ViewModelLocator();
var mainVm = new MainWindowViewModel(locator); var mainVm = new MainWindowViewModel(locator);
DataContext = mainVm; DataContext = mainVm;

View File

@@ -4,9 +4,10 @@
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:Valheim_Dashboard.ViewModels" xmlns:vm="clr-namespace:Valheim_Dashboard.ViewModels"
mc:Ignorable="d" d:DesignWidth="1280" d:DesignHeight="800" mc:Ignorable="d" d:DesignWidth="1424" d:DesignHeight="714"
x:Class="Valheim_Dashboard.Views.ServerDashboardView" x:Class="Valheim_Dashboard.Views.ServerDashboardView"
x:DataType="vm:ServerDashboardViewModel"> x:DataType="vm:ServerDashboardViewModel"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit">
<Grid ColumnDefinitions="2*,3*"> <Grid ColumnDefinitions="2*,3*">
@@ -14,11 +15,13 @@
<StackPanel Margin="20" Spacing="20"> <StackPanel Margin="20" Spacing="20">
<!-- BepInEx Status --> <!-- BepInEx Status -->
<Border BorderBrush="Gray" BorderThickness="2" CornerRadius="12" Padding="20"> <Border BorderBrush="Gray" BorderThickness="2" CornerRadius="12" Padding="20">
<StackPanel Spacing="10" Height="150"> <StackPanel Spacing="10" Height="120">
<TextBlock Text="BepInEx Status" FontSize="28" FontWeight="Bold"/> <TextBlock Text="BepInEx Status" FontSize="28" FontWeight="Bold"/>
<TextBlock Text="{Binding BepInExStatus}" FontSize="20"/> <TextBlock Text="{Binding BepInExStatus}" FontSize="20"/>
<ProgressBar IsVisible="{Binding IsLoading}" /> <ProgressBar IsVisible="{Binding IsLoading}" />
<Button Content="Installieren" <Button Content="Installieren"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
Command="{Binding InstallBepInExCommand}" Command="{Binding InstallBepInExCommand}"
IsVisible="{Binding ShowInstallButton}" IsVisible="{Binding ShowInstallButton}"
Height="80"/> Height="80"/>
@@ -26,6 +29,8 @@
Command="{Binding UpdateBepInExCommand}" Command="{Binding UpdateBepInExCommand}"
IsVisible="{Binding ShowUpdateButton}" IsVisible="{Binding ShowUpdateButton}"
Height="80"/> Height="80"/>
<ProgressBar Minimum="0" Maximum="100" Value="{Binding ProgressValue}" IsVisible="{Binding IsProgress}" Height="20"/>
<TextBlock Text="{Binding ProgressText}" Margin="0,5,0,0" IsVisible="{Binding IsProgress}"/>
</StackPanel> </StackPanel>
</Border> </Border>
@@ -33,7 +38,7 @@
<Border BorderBrush="Gray" BorderThickness="2" CornerRadius="12" Padding="20"> <Border BorderBrush="Gray" BorderThickness="2" CornerRadius="12" Padding="20">
<StackPanel Height="450"> <StackPanel Height="450">
<TextBlock Text="Mods" FontSize="28" FontWeight="Bold"/> <TextBlock Text="Mods" FontSize="28" FontWeight="Bold"/>
<ListBox ItemsSource="{Binding Mods}" SelectedItem="{Binding SelectedMod}" Height="380"> <ListBox ItemsSource="{Binding Mods}" SelectedItem="{Binding SelectedMod}" Height="330">
<ListBox.ItemTemplate> <ListBox.ItemTemplate>
<DataTemplate> <DataTemplate>
@@ -45,7 +50,7 @@
</ListBox.ItemTemplate> </ListBox.ItemTemplate>
</ListBox> </ListBox>
<Grid> <Grid Margin="0,20,0,0">
<Button Content="Mod hochladen" Command="{Binding UploadModCommand}" Height="80" HorizontalAlignment="Left"/> <Button Content="Mod hochladen" Command="{Binding UploadModCommand}" Height="80" HorizontalAlignment="Left"/>
<Button Content="Aus Store installieren" Command="{Binding InstallFromStoreCommand}" Height="80" HorizontalAlignment="Right"/> <Button Content="Aus Store installieren" Command="{Binding InstallFromStoreCommand}" Height="80" HorizontalAlignment="Right"/>
@@ -57,7 +62,19 @@
<!-- Rechte Spalte (Config Editor) --> <!-- Rechte Spalte (Config Editor) -->
<StackPanel Grid.Column="1" Margin="20" Spacing="20"> <StackPanel Grid.Column="1" Margin="20" Spacing="20">
<TextBlock Text="{Binding SelectedMod.Name}" FontSize="28" FontWeight="Bold"/> <TextBlock Text="{Binding SelectedMod.Name}" FontSize="28" FontWeight="Bold"/>
<TextBox Text="{Binding SelectedModConfig}" AcceptsReturn="True" FontSize="20" Height="550"/> <ae:TextEditor
Document="{Binding ConfigDocument}"
x:Name="MyEditorName"
IsVisible="True"
BorderBrush="Black"
BorderThickness="20"
ShowLineNumbers="True"
Background="Red"
Foreground="Yellow"
FontFamily="Cascadia Code, Consolas, Menlo, monospace"
FontSize="20"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto" Height="520" />
<Grid> <Grid>
<Button Content="Speichern" Command="{Binding SaveConfigCommand}" Height="80" HorizontalAlignment="Left"/> <Button Content="Speichern" Command="{Binding SaveConfigCommand}" Height="80" HorizontalAlignment="Left"/>
<Button Content="Mod entfernen" Command="{Binding RemoveModCommand}" Height="80" Background="Red" HorizontalAlignment="Right"/> <Button Content="Mod entfernen" Command="{Binding RemoveModCommand}" Height="80" Background="Red" HorizontalAlignment="Right"/>

View File

@@ -1,6 +1,7 @@
using Avalonia; using Avalonia;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Markup.Xaml; using Avalonia.Markup.Xaml;
using System.Diagnostics;
using Valheim_Dashboard.ViewModels; using Valheim_Dashboard.ViewModels;
namespace Valheim_Dashboard.Views; namespace Valheim_Dashboard.Views;
@@ -10,5 +11,10 @@ public partial class ServerDashboardView : UserControl
public ServerDashboardView() public ServerDashboardView()
{ {
InitializeComponent(); InitializeComponent();
this.AttachedToVisualTree += (_, __) =>
{
var te = this.FindControl<AvaloniaEdit.TextEditor>("MyEditorName");
Debug.WriteLine("TE Document text = " + te?.Document?.Text?.Length);
};
} }
} }