diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 31990cd..0f11e53 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,6 +1,7 @@ name: Release Pipeline on: + workflow_dispatch: workflow_run: workflows: ["Continuous Integration"] types: @@ -13,13 +14,16 @@ permissions: jobs: release-build: - if: github.event.workflow_run.conclusion == 'success' + if: github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success' strategy: matrix: include: - os: ubuntu-latest rid: linux-x64 archive_ext: tar.gz + - os: ubuntu-latest + rid: linux-arm64 + archive_ext: tar.gz - os: macos-latest rid: osx-x64 archive_ext: zip @@ -94,6 +98,12 @@ jobs: run: | tar -czf PocketMC-${{ matrix.rid }}.tar.gz -C publish . + - name: Package Linux Debian Package (.deb) + if: steps.check_channel.outputs.skip == 'false' && matrix.os == 'ubuntu-latest' + run: | + chmod +x scripts/build-deb.sh + ./scripts/build-deb.sh ${{ matrix.rid }} ${{ steps.config.outputs.version }} publish + - name: Package Release Archive (zip) if: steps.check_channel.outputs.skip == 'false' && matrix.archive_ext == 'zip' run: | @@ -114,6 +124,7 @@ jobs: path: | PocketMC-${{ matrix.rid }}.${{ matrix.archive_ext }} PocketMC-*.dmg + pocketmc_*.deb create-release: needs: release-build @@ -171,11 +182,13 @@ jobs: body: "Official cross-platform production release of PocketMC for Linux and macOS." files: | artifacts/PocketMC-linux-x64.tar.gz + artifacts/PocketMC-linux-arm64.tar.gz + artifacts/pocketmc_*.deb artifacts/PocketMC-osx-x64.zip artifacts/PocketMC-osx-arm64.zip artifacts/PocketMC-osx-x64.dmg artifacts/PocketMC-osx-arm64.dmg draft: false - prerelease: false + prerelease: ${{ contains(steps.config.outputs.version, 'beta') || contains(steps.config.outputs.version, 'rc') }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index a896ca8..0f6859c 100755 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,4 @@ PocketMC-linux-x64.tar.gz PocketMC-*.tar.gz PocketMC-*.zip .planning/ +.ai/ diff --git a/PocketMC.App/App.axaml b/PocketMC.App/App.axaml index 8572e7c..81fae07 100755 --- a/PocketMC.App/App.axaml +++ b/PocketMC.App/App.axaml @@ -10,32 +10,108 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/PocketMC.App/App.axaml.cs b/PocketMC.App/App.axaml.cs index 5a80795..1f825e0 100755 --- a/PocketMC.App/App.axaml.cs +++ b/PocketMC.App/App.axaml.cs @@ -42,8 +42,28 @@ public override void OnFrameworkInitializationCompleted() desktop.MainWindow = Services.GetRequiredService(); } + if (desktop.MainWindow != null) + { + desktop.MainWindow.Loaded += async (s, e) => + { + try + { + var whatsNewService = Services.GetRequiredService(); + if (whatsNewService.ShouldShow()) + { + var whatsNewWin = new WhatsNewWindow(whatsNewService); + await whatsNewWin.ShowDialog(desktop.MainWindow); + } + } + catch { } + }; + } + try { + var rebootScheduler = Services.GetService(); + rebootScheduler?.Start(); + var playitClient = Services.GetRequiredService(); var tunnelManager = Services.GetRequiredService(); if (playitClient.HasPartnerConnection()) @@ -52,9 +72,65 @@ public override void OnFrameworkInitializationCompleted() } } catch { } + + desktop.Exit += async (sender, args) => + { + try + { + var rebootScheduler = Services.GetService(); + rebootScheduler?.Stop(); + + var procRunner = Services.GetService(); + if (procRunner != null) + { + await procRunner.StopAllAsync(); + } + + var tunnelManager = Services.GetService(); + if (tunnelManager != null) + { + await tunnelManager.StopAllTunnelsAsync(); + } + } + catch { } + }; } base.OnFrameworkInitializationCompleted(); } + + private void TrayIcon_Clicked(object? sender, EventArgs e) + { + RestoreMainWindow(); + } + + private void TrayOpen_Clicked(object? sender, EventArgs e) + { + RestoreMainWindow(); + } + + private void TrayQuit_Clicked(object? sender, EventArgs e) + { + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + { + desktop.Shutdown(); + } + } + + private void RestoreMainWindow() + { + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop && desktop.MainWindow != null) + { + if (!desktop.MainWindow.IsVisible) + { + desktop.MainWindow.Show(); + } + if (desktop.MainWindow.WindowState == Avalonia.Controls.WindowState.Minimized) + { + desktop.MainWindow.WindowState = Avalonia.Controls.WindowState.Normal; + } + desktop.MainWindow.Activate(); + } + } } } diff --git a/PocketMC.App/Assets/WhatsNew.txt b/PocketMC.App/Assets/WhatsNew.txt new file mode 100644 index 0000000..2d26216 --- /dev/null +++ b/PocketMC.App/Assets/WhatsNew.txt @@ -0,0 +1,19 @@ +VERSION=1.0.4-beta.1 + +[NEW FEATURES & LINUX/MACOS PARITY] +Exact PocketMC Windows UI and UX parity delivered for Linux and macOS. +TitleBar live System RAM usage telemetry with threshold alert coloring. +Full Remote Control subsystem with auto-start, Cloudflare/Playit tunnels, and PBKDF2 authentication. +Cross-platform AppClipboard service supporting Wayland (wl-copy), X11 (xclip/xsel), and macOS (pbcopy). + +[IMPROVEMENTS] +Accurate instance card state synchronization for running servers with emerald status indicators. +Platform-aware title bar margin adjustment ensuring flush right-edge alignment on Linux and macOS. +Enforced word wrapping on server console logs eliminating horizontal scrollbars. +Interactive Ports Map visualizing local ports, RCON, Query, Simple Voice Chat UDP, and Playit public endpoints. + +[FIXES & STABILITY] +Fixed session.lock DirectoryLock LockException crash caused by duplicate process execution and orphaned child processes. +Guaranteed entireProcessTree process termination on server shutdown and stop timeouts. +Configurable server crash auto-restart preventing infinite crash loops on fatal errors. +Console Copy Logs button with visual confirmation and dynamic checkmark feedback. diff --git a/PocketMC.App/Assets/avatar_divyviradiya.png b/PocketMC.App/Assets/avatar_divyviradiya.png new file mode 100644 index 0000000..b742d07 Binary files /dev/null and b/PocketMC.App/Assets/avatar_divyviradiya.png differ diff --git a/PocketMC.App/Assets/avatar_johndinglesin.png b/PocketMC.App/Assets/avatar_johndinglesin.png new file mode 100644 index 0000000..1f9f1da Binary files /dev/null and b/PocketMC.App/Assets/avatar_johndinglesin.png differ diff --git a/PocketMC.App/Assets/avatar_nexvice.png b/PocketMC.App/Assets/avatar_nexvice.png new file mode 100644 index 0000000..fb01ae5 Binary files /dev/null and b/PocketMC.App/Assets/avatar_nexvice.png differ diff --git a/PocketMC.App/Assets/avatar_sahajitaliya.png b/PocketMC.App/Assets/avatar_sahajitaliya.png new file mode 100644 index 0000000..3d42e5f Binary files /dev/null and b/PocketMC.App/Assets/avatar_sahajitaliya.png differ diff --git a/PocketMC.App/Assets/dark_dirt.png b/PocketMC.App/Assets/dark_dirt.png new file mode 100644 index 0000000..0348629 Binary files /dev/null and b/PocketMC.App/Assets/dark_dirt.png differ diff --git a/PocketMC.App/Assets/default_wallpaper.png b/PocketMC.App/Assets/default_wallpaper.png new file mode 100644 index 0000000..ed1036b Binary files /dev/null and b/PocketMC.App/Assets/default_wallpaper.png differ diff --git a/PocketMC.App/Assets/logo.png b/PocketMC.App/Assets/logo.png index 4d0cac2..ed78513 100755 Binary files a/PocketMC.App/Assets/logo.png and b/PocketMC.App/Assets/logo.png differ diff --git a/PocketMC.App/Assets/logo_highres.png b/PocketMC.App/Assets/logo_highres.png new file mode 100644 index 0000000..4d0cac2 Binary files /dev/null and b/PocketMC.App/Assets/logo_highres.png differ diff --git a/PocketMC.App/Assets/splash.png b/PocketMC.App/Assets/splash.png new file mode 100644 index 0000000..842a070 Binary files /dev/null and b/PocketMC.App/Assets/splash.png differ diff --git a/PocketMC.App/Controls/AdaptiveGridPanel.cs b/PocketMC.App/Controls/AdaptiveGridPanel.cs new file mode 100644 index 0000000..b12b7af --- /dev/null +++ b/PocketMC.App/Controls/AdaptiveGridPanel.cs @@ -0,0 +1,164 @@ +using System; +using System.Collections.Generic; +using Avalonia; +using Avalonia.Controls; + +namespace PocketMC.App.Controls +{ + /// + /// A high-performance responsive Avalonia panel that lays out children in an adaptive grid. + /// Calculates the optimal column count based on MinColumnWidth and stretches + /// all children within each column to evenly fill available width with no right-side dead space. + /// + public class AdaptiveGridPanel : Panel + { + public static readonly StyledProperty MinColumnWidthProperty = + AvaloniaProperty.Register(nameof(MinColumnWidth), 340.0); + + public static readonly StyledProperty HorizontalSpacingProperty = + AvaloniaProperty.Register(nameof(HorizontalSpacing), 16.0); + + public static readonly StyledProperty VerticalSpacingProperty = + AvaloniaProperty.Register(nameof(VerticalSpacing), 16.0); + + static AdaptiveGridPanel() + { + AffectsMeasure(MinColumnWidthProperty, HorizontalSpacingProperty, VerticalSpacingProperty); + AffectsArrange(MinColumnWidthProperty, HorizontalSpacingProperty, VerticalSpacingProperty); + } + + public double MinColumnWidth + { + get => GetValue(MinColumnWidthProperty); + set => SetValue(MinColumnWidthProperty, value); + } + + public double HorizontalSpacing + { + get => GetValue(HorizontalSpacingProperty); + set => SetValue(HorizontalSpacingProperty, value); + } + + public double VerticalSpacing + { + get => GetValue(VerticalSpacingProperty); + set => SetValue(VerticalSpacingProperty, value); + } + + protected override Size MeasureOverride(Size availableSize) + { + var visibleChildren = GetVisibleChildren(); + if (visibleChildren.Count == 0) + { + return new Size(0, 0); + } + + double availableWidth = double.IsPositiveInfinity(availableSize.Width) || double.IsNaN(availableSize.Width) + ? MinColumnWidth * visibleChildren.Count + HorizontalSpacing * (visibleChildren.Count - 1) + : availableSize.Width; + + int columns = CalculateColumnCount(availableWidth); + double itemWidth = CalculateItemWidth(availableWidth, columns); + + var childConstraint = new Size(itemWidth, double.PositiveInfinity); + + double totalHeight = 0; + double currentRowMaxHeight = 0; + + for (int i = 0; i < visibleChildren.Count; i++) + { + var child = visibleChildren[i]; + child.Measure(childConstraint); + + currentRowMaxHeight = Math.Max(currentRowMaxHeight, child.DesiredSize.Height); + + if ((i + 1) % columns == 0 || i == visibleChildren.Count - 1) + { + totalHeight += currentRowMaxHeight; + if (i < visibleChildren.Count - 1) + { + totalHeight += VerticalSpacing; + } + currentRowMaxHeight = 0; + } + } + + return new Size(availableWidth, totalHeight); + } + + protected override Size ArrangeOverride(Size finalSize) + { + var visibleChildren = GetVisibleChildren(); + if (visibleChildren.Count == 0) + { + return finalSize; + } + + int columns = CalculateColumnCount(finalSize.Width); + double itemWidth = CalculateItemWidth(finalSize.Width, columns); + + var rowHeights = new List(); + double currentRowMaxHeight = 0; + + for (int i = 0; i < visibleChildren.Count; i++) + { + currentRowMaxHeight = Math.Max(currentRowMaxHeight, visibleChildren[i].DesiredSize.Height); + + if ((i + 1) % columns == 0 || i == visibleChildren.Count - 1) + { + rowHeights.Add(currentRowMaxHeight); + currentRowMaxHeight = 0; + } + } + + double y = 0; + int rowIndex = 0; + + for (int i = 0; i < visibleChildren.Count; i++) + { + int colIndex = i % columns; + double x = colIndex * (itemWidth + HorizontalSpacing); + double rowHeight = rowHeights[rowIndex]; + + visibleChildren[i].Arrange(new Rect(x, y, itemWidth, rowHeight)); + + if (colIndex == columns - 1 || i == visibleChildren.Count - 1) + { + y += rowHeight + VerticalSpacing; + rowIndex++; + } + } + + return finalSize; + } + + private int CalculateColumnCount(double availableWidth) + { + if (availableWidth <= 0 || MinColumnWidth <= 0) return 1; + + int count = (int)Math.Floor((availableWidth + HorizontalSpacing) / (MinColumnWidth + HorizontalSpacing)); + return Math.Max(1, count); + } + + private double CalculateItemWidth(double availableWidth, int columns) + { + if (columns <= 1) return Math.Max(1.0, availableWidth); + + double totalSpacing = (columns - 1) * HorizontalSpacing; + return Math.Max(1.0, (availableWidth - totalSpacing) / columns); + } + + private List GetVisibleChildren() + { + var list = new List(Children.Count); + foreach (var child in Children) + { + if (child != null && child.IsVisible) + { + list.Add(child); + } + } + return list; + } + } +} diff --git a/PocketMC.App/Converters/MinecraftMotdConverter.cs b/PocketMC.App/Converters/MinecraftMotdConverter.cs new file mode 100644 index 0000000..7f82d38 --- /dev/null +++ b/PocketMC.App/Converters/MinecraftMotdConverter.cs @@ -0,0 +1,196 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.Json; +using Avalonia.Controls; +using Avalonia.Controls.Documents; +using Avalonia.Data.Converters; +using Avalonia.Media; + +namespace PocketMC.App.Converters +{ + public class MinecraftMotdConverter : IValueConverter + { + private static readonly Dictionary ColorMap = new() + { + { '0', new SolidColorBrush(Color.FromRgb(0, 0, 0)) }, + { '1', new SolidColorBrush(Color.FromRgb(0, 0, 170)) }, + { '2', new SolidColorBrush(Color.FromRgb(0, 170, 0)) }, + { '3', new SolidColorBrush(Color.FromRgb(0, 170, 170)) }, + { '4', new SolidColorBrush(Color.FromRgb(170, 0, 0)) }, + { '5', new SolidColorBrush(Color.FromRgb(170, 0, 170)) }, + { '6', new SolidColorBrush(Color.FromRgb(255, 170, 0)) }, + { '7', new SolidColorBrush(Color.FromRgb(170, 170, 170)) }, + { '8', new SolidColorBrush(Color.FromRgb(85, 85, 85)) }, + { '9', new SolidColorBrush(Color.FromRgb(85, 85, 255)) }, + { 'a', new SolidColorBrush(Color.FromRgb(85, 255, 85)) }, + { 'b', new SolidColorBrush(Color.FromRgb(85, 255, 255)) }, + { 'c', new SolidColorBrush(Color.FromRgb(255, 85, 85)) }, + { 'd', new SolidColorBrush(Color.FromRgb(255, 85, 255)) }, + { 'e', new SolidColorBrush(Color.FromRgb(255, 255, 85)) }, + { 'f', new SolidColorBrush(Color.FromRgb(255, 255, 255)) } + }; + + private static readonly IBrush DefaultBrush = new SolidColorBrush(Color.FromRgb(170, 170, 170)); + + public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) + { + var text = value as string; + var textBlock = new TextBlock { TextWrapping = TextWrapping.Wrap }; + + if (string.IsNullOrWhiteSpace(text)) + { + textBlock.Text = "A Minecraft Server"; + textBlock.Foreground = DefaultBrush; + return textBlock; + } + + text = text.Trim(); + + // Detect JSON MOTD format + if (text.StartsWith("{")) + { + try + { + using var doc = JsonDocument.Parse(text); + ParseJsonMotd(doc.RootElement, textBlock); + return textBlock; + } + catch (JsonException) + { + // Fall back to legacy parsing + } + } + + // Normalise prefixes to § + text = text.Replace("\\u00A7", "§"); + text = text.Replace("&", "§"); + text = text.Replace("\\n", "\n"); + + ParseLegacyMotd(text, textBlock); + return textBlock; + } + + public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) + { + throw new NotSupportedException(); + } + + private static void ParseLegacyMotd(string text, TextBlock textBlock) + { + IBrush currentBrush = DefaultBrush; + bool isBold = false; + bool isItalic = false; + bool isUnderline = false; + bool isStrikethrough = false; + + int i = 0; + while (i < text.Length) + { + if (text[i] == '§' && i + 1 < text.Length) + { + char code = char.ToLowerInvariant(text[i + 1]); + i += 2; + + if (ColorMap.TryGetValue(code, out var brush)) + { + currentBrush = brush; + isBold = false; + isItalic = false; + isUnderline = false; + isStrikethrough = false; + } + else + { + switch (code) + { + case 'l': isBold = true; break; + case 'o': isItalic = true; break; + case 'n': isUnderline = true; break; + case 'm': isStrikethrough = true; break; + case 'r': + currentBrush = DefaultBrush; + isBold = false; + isItalic = false; + isUnderline = false; + isStrikethrough = false; + break; + } + } + } + else + { + int nextSection = text.IndexOf('§', i); + string chunk = nextSection == -1 ? text.Substring(i) : text.Substring(i, nextSection - i); + i = nextSection == -1 ? text.Length : nextSection; + + if (!string.IsNullOrEmpty(chunk)) + { + var run = new Run(chunk) + { + Foreground = currentBrush, + FontWeight = isBold ? FontWeight.Bold : FontWeight.Normal, + FontStyle = isItalic ? FontStyle.Italic : FontStyle.Normal + }; + + if (isUnderline && isStrikethrough) + { + run.TextDecorations = TextDecorations.Underline; + } + else if (isUnderline) + { + run.TextDecorations = TextDecorations.Underline; + } + else if (isStrikethrough) + { + run.TextDecorations = TextDecorations.Strikethrough; + } + + textBlock.Inlines ??= new InlineCollection(); + textBlock.Inlines.Add(run); + } + } + } + } + + private static void ParseJsonMotd(JsonElement element, TextBlock textBlock) + { + textBlock.Inlines ??= new InlineCollection(); + if (element.ValueKind == JsonValueKind.String) + { + textBlock.Inlines.Add(new Run(element.GetString() ?? string.Empty) { Foreground = DefaultBrush }); + return; + } + + if (element.ValueKind == JsonValueKind.Object) + { + if (element.TryGetProperty("text", out var textProp)) + { + string txt = textProp.GetString() ?? string.Empty; + IBrush brush = DefaultBrush; + if (element.TryGetProperty("color", out var colorProp)) + { + string colorStr = colorProp.GetString() ?? string.Empty; + if (colorStr.StartsWith("#") && Color.TryParse(colorStr, out var parsedColor)) + { + brush = new SolidColorBrush(parsedColor); + } + } + + if (!string.IsNullOrEmpty(txt)) + { + textBlock.Inlines.Add(new Run(txt) { Foreground = brush }); + } + } + + if (element.TryGetProperty("extra", out var extraProp) && extraProp.ValueKind == JsonValueKind.Array) + { + foreach (var item in extraProp.EnumerateArray()) + { + ParseJsonMotd(item, textBlock); + } + } + } + } + } +} diff --git a/PocketMC.App/Interfaces/ISupportsKeyboardBackNavigation.cs b/PocketMC.App/Interfaces/ISupportsKeyboardBackNavigation.cs new file mode 100644 index 0000000..2a98bb7 --- /dev/null +++ b/PocketMC.App/Interfaces/ISupportsKeyboardBackNavigation.cs @@ -0,0 +1,6 @@ +namespace PocketMC.App.Interfaces; + +public interface ISupportsKeyboardBackNavigation +{ + bool HandleBackNavigation(); +} diff --git a/PocketMC.App/Interfaces/ITitleBarContextSource.cs b/PocketMC.App/Interfaces/ITitleBarContextSource.cs new file mode 100644 index 0000000..52fd876 --- /dev/null +++ b/PocketMC.App/Interfaces/ITitleBarContextSource.cs @@ -0,0 +1,8 @@ +namespace PocketMC.App.Interfaces; + +public interface ITitleBarContextSource +{ + string? TitleBarTitle { get; } + string? TitleBarSubtitle { get; } + string? TitleBarStatusDotColor { get; } +} diff --git a/PocketMC.App/Navigation/AppNavigationService.cs b/PocketMC.App/Navigation/AppNavigationService.cs new file mode 100644 index 0000000..1eccf69 --- /dev/null +++ b/PocketMC.App/Navigation/AppNavigationService.cs @@ -0,0 +1,135 @@ +using System; +using PocketMC.App.Interfaces; + +namespace PocketMC.App.Navigation; + +public sealed class AppNavigationService : IAppNavigationService +{ + private readonly IServiceProvider? _serviceProvider; + private readonly ControlledNavigationStack _stack = new(); + private IShellHost? _shellHost; + + public event Action? NavigationChanged; + + public bool CanNavigateBack => _stack.CanNavigateBack; + public bool CanNavigateForward => _stack.CanNavigateForward; + public string? CurrentBreadcrumb => _stack.Current?.Breadcrumb; + public DetailRouteKind? CurrentRouteKind => _stack.Current?.RouteKind; + + public AppNavigationService(IServiceProvider? serviceProvider = null) + { + _serviceProvider = serviceProvider; + } + + public void Initialize(IShellHost shellHost) + { + _shellHost = shellHost; + } + + public bool NavigateToDashboard() + { + if (_shellHost == null) return false; + object page = "Dashboard"; + if (_serviceProvider != null) + { + var vm = _serviceProvider.GetService(typeof(ViewModels.DashboardViewModel)); + if (vm != null) page = vm; + } + _stack.Push(page, "Dashboard", DetailRouteKind.Dashboard, DetailBackNavigation.Dashboard, clearDetailStack: true); + ApplyCurrent(); + return true; + } + + public bool NavigateToTunnel() + { + if (_shellHost == null) return false; + object page = "Tunnel"; + if (_serviceProvider != null) + { + var vm = _serviceProvider.GetService(typeof(ViewModels.TunnelViewModel)); + if (vm != null) page = vm; + } + _stack.Push(page, "Tunnel", DetailRouteKind.Tunnel, DetailBackNavigation.Dashboard, clearDetailStack: true); + ApplyCurrent(); + return true; + } + + public bool NavigateToNews() + { + if (_shellHost == null) return false; + object page = "News"; + if (_serviceProvider != null) + { + var vm = _serviceProvider.GetService(typeof(ViewModels.NewsViewModel)); + if (vm != null) page = vm; + } + _stack.Push(page, "Community News", DetailRouteKind.News, DetailBackNavigation.Dashboard); + ApplyCurrent(); + return true; + } + + public bool NavigateToDetailPage( + object page, + string breadcrumbLabel, + DetailRouteKind routeKind, + DetailBackNavigation backNavigation, + bool clearDetailStack = false) + { + if (_shellHost == null) return false; + + _stack.Push(page, breadcrumbLabel, routeKind, backNavigation, clearDetailStack); + ApplyCurrent(); + return true; + } + + public bool NavigateBack() + { + // First, check if current page handles keyboard back navigation internally + if (_stack.Current?.Page is ISupportsKeyboardBackNavigation backHandler && backHandler.HandleBackNavigation()) + { + return true; + } + + var prev = _stack.NavigateBack(); + if (prev != null) + { + ApplyCurrent(); + return true; + } + + return false; + } + + public bool NavigateForward() + { + var next = _stack.NavigateForward(); + if (next != null) + { + ApplyCurrent(); + return true; + } + + return false; + } + + private void ApplyCurrent() + { + var entry = _stack.Current; + if (entry != null && _shellHost != null) + { + _shellHost.SetContent(entry.Page); + _shellHost.UpdateBreadcrumb(entry.Breadcrumb); + + if (entry.Page is ITitleBarContextSource titleBarSource) + { + _shellHost.SetTitleBarContext(titleBarSource.TitleBarTitle, titleBarSource.TitleBarSubtitle, titleBarSource.TitleBarStatusDotColor); + } + else + { + _shellHost.SetTitleBarContext(null, null, null); + } + } + + NavigationChanged?.Invoke(); + } +} diff --git a/PocketMC.App/Navigation/ControlledNavigationStack.cs b/PocketMC.App/Navigation/ControlledNavigationStack.cs new file mode 100644 index 0000000..2d47caa --- /dev/null +++ b/PocketMC.App/Navigation/ControlledNavigationStack.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Generic; + +namespace PocketMC.App.Navigation; + +public sealed class ControlledNavigationStack +{ + private readonly List _backStack = new(); + private readonly Stack _forwardStack = new(); + private NavigationEntry? _current; + + public bool CanNavigateBack => _backStack.Count > 0; + public bool CanNavigateForward => _forwardStack.Count > 0; + + public NavigationEntry? Current => _current; + + public void Push(object page, string breadcrumb, DetailRouteKind routeKind, DetailBackNavigation backNavigation, bool clearDetailStack = false) + { + var newEntry = new NavigationEntry(page, breadcrumb, routeKind, backNavigation); + + if (clearDetailStack) + { + _backStack.Clear(); + _forwardStack.Clear(); + _current = newEntry; + return; + } + + if (_current != null) + { + _backStack.Add(_current); + } + + _forwardStack.Clear(); + _current = newEntry; + } + + public NavigationEntry? NavigateBack() + { + if (!CanNavigateBack) + { + return null; + } + + if (_current != null) + { + _forwardStack.Push(_current); + } + + int lastIndex = _backStack.Count - 1; + var previous = _backStack[lastIndex]; + _backStack.RemoveAt(lastIndex); + + _current = previous; + return previous; + } + + public NavigationEntry? NavigateForward() + { + if (!CanNavigateForward) + { + return null; + } + + if (_current != null) + { + _backStack.Add(_current); + } + + var next = _forwardStack.Pop(); + _current = next; + return next; + } + + public void Clear() + { + _backStack.Clear(); + _forwardStack.Clear(); + _current = null; + } +} diff --git a/PocketMC.App/Navigation/IAppNavigationService.cs b/PocketMC.App/Navigation/IAppNavigationService.cs new file mode 100644 index 0000000..c9464e0 --- /dev/null +++ b/PocketMC.App/Navigation/IAppNavigationService.cs @@ -0,0 +1,78 @@ +using System; + +namespace PocketMC.App.Navigation; + +public enum DetailRouteKind +{ + Dashboard, + Tunnel, + RemoteControl, + News, + NewInstance, + ServerSettings, + PluginBrowser, + MapBrowser, + ServerConsole, + PlayerManagement, + ImageCrop, + PortsMap, + InstanceImport, + InstanceExport, + PlayitNetworkStatus, + AiDiagnostic, + WhatsNew, + Settings, + Runtimes, + About +} + +public enum DetailBackNavigation +{ + Dashboard, + Tunnel, + PreviousDetail +} + +public sealed class NavigationEntry +{ + public object Page { get; } + public string Breadcrumb { get; } + public DetailRouteKind RouteKind { get; } + public DetailBackNavigation BackNavigation { get; } + + public NavigationEntry(object page, string breadcrumb, DetailRouteKind routeKind, DetailBackNavigation backNavigation) + { + Page = page; + Breadcrumb = breadcrumb; + RouteKind = routeKind; + BackNavigation = backNavigation; + } +} + +public interface IShellHost +{ + void SetContent(object page); + void UpdateBreadcrumb(string breadcrumb); + void SetTitleBarContext(string? title, string? subtitle, string? statusDotColor); +} + +public interface IAppNavigationService +{ + void Initialize(IShellHost shellHost); + bool NavigateToDashboard(); + bool NavigateToTunnel(); + bool NavigateToNews(); + bool NavigateToDetailPage( + object page, + string breadcrumbLabel, + DetailRouteKind routeKind, + DetailBackNavigation backNavigation, + bool clearDetailStack = false); + bool NavigateBack(); + bool NavigateForward(); + bool CanNavigateBack { get; } + bool CanNavigateForward { get; } + string? CurrentBreadcrumb { get; } + DetailRouteKind? CurrentRouteKind { get; } + event Action? NavigationChanged; +} diff --git a/PocketMC.App/PocketMC.App.csproj b/PocketMC.App/PocketMC.App.csproj index 3198853..779e516 100755 --- a/PocketMC.App/PocketMC.App.csproj +++ b/PocketMC.App/PocketMC.App.csproj @@ -16,13 +16,15 @@ - + + + diff --git a/PocketMC.App/Program.cs b/PocketMC.App/Program.cs index e353bf6..cb15246 100755 --- a/PocketMC.App/Program.cs +++ b/PocketMC.App/Program.cs @@ -1,10 +1,17 @@ using System; +using System.Linq; using Avalonia; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using PocketMC.Core.Services; using PocketMC.Infrastructure.Services; using PocketMC.Platform.Services; +using PocketMC.Platform.Lifecycle; +using PocketMC.Platform.Notifications; +using PocketMC.Platform.Integrations; +using PocketMC.Infrastructure.Power; +using PocketMC.App.Navigation; +using PocketMC.App.Services; using PocketMC.App.ViewModels; using PocketMC.App.Views; @@ -72,7 +79,10 @@ public static IHostBuilder CreateHostBuilder(string[] args) => services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); @@ -82,10 +92,18 @@ public static IHostBuilder CreateHostBuilder(string[] args) => // New Phase 4 Infrastructure services (Backups & Marketplace) services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); @@ -99,11 +117,22 @@ public static IHostBuilder CreateHostBuilder(string[] args) => services.AddSingleton(); services.AddSingleton(); + // Server Version Updates (Transactional Upgrades & Rollbacks) + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + // Phase 5 Remote Control & Tunnels services.AddSingleton(); services.AddSingleton(); services.AddSingleton(sp => new PocketMC.RemoteControl.Services.RemoteAuditLogService(sp.GetRequiredService().GetLogsDirectory())); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddHostedService(sp => sp.GetRequiredService()); @@ -113,11 +142,62 @@ public static IHostBuilder CreateHostBuilder(string[] args) => services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); + + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(sp => new DashboardActionsViewModel( + sp.GetRequiredService(), + sp.GetRequiredService(), + sp.GetRequiredService(), + navigationService: sp.GetService(), + serviceProvider: sp)); // ViewModels & Views + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(sp => + new ServerSleepPreventionCoordinator( + sp.GetRequiredService(), + () => sp.GetRequiredService().Settings, + () => sp.GetRequiredService().GetRunningSlugs().Count, + sp.GetRequiredService>(), + sp.GetService())); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddTransient(); - services.AddSingleton(); + services.AddTransient(); + services.AddTransient(); + services.AddSingleton(sp => new DashboardViewModel( + sp.GetRequiredService(), + sp.GetRequiredService(), + sp.GetRequiredService(), + sp.GetRequiredService(), + sp.GetRequiredService(), + sp.GetRequiredService(), + sp.GetRequiredService(), + sp.GetRequiredService(), + sp.GetService(), + sp.GetService(), + sp, + sp.GetRequiredService(), + sp.GetRequiredService(), + sp.GetRequiredService(), + sp.GetService(), + sp.GetService())); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -137,10 +217,24 @@ public static IHostBuilder CreateHostBuilder(string[] args) => services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddSingleton(); + services.AddTransient(); + services.AddSingleton(); + services.AddSingleton(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); }); diff --git a/PocketMC.App/Services/AccentColorService.cs b/PocketMC.App/Services/AccentColorService.cs new file mode 100644 index 0000000..2886708 --- /dev/null +++ b/PocketMC.App/Services/AccentColorService.cs @@ -0,0 +1,185 @@ +using System; +using System.Globalization; +using Avalonia; +using Avalonia.Media; +using PocketMC.Core.Models; +using PocketMC.Core.Services; + +namespace PocketMC.App.Services; + +public sealed class AccentColorService +{ + public const string AutomaticMode = "Automatic"; + public const string CustomMode = "Custom"; + public const string DefaultCustomAccentColor = "#008B00"; + + private static readonly Color FallbackSystemAccent = Color.FromRgb(0x00, 0x8B, 0x00); + private readonly ISettingsService? _settingsService; + + public event Action? AccentChanged; + public static event Action? GlobalAccentChanged; + + public AccentColorService(ISettingsService? settingsService = null) + { + _settingsService = settingsService; + } + + public void ApplyCurrentAccent() + { + var settings = _settingsService?.Settings; + if (settings != null && IsCustomMode(settings.AccentColorMode) && + TryParseHexColor(settings.CustomAccentColor, out Color customColor, out _)) + { + ApplyCustomAccent(customColor); + return; + } + + ApplySystemAccent(); + } + + public void ApplyCustomAccent(Color color) + { + ApplyAccentToApplication(color); + NotifyAccentChanged(color); + } + + public void ApplySystemAccent() + { + Color systemColor = GetSystemAccentColor(); + ApplyAccentToApplication(systemColor); + NotifyAccentChanged(systemColor); + } + + public void ReassertAccent() + { + var settings = _settingsService?.Settings; + if (settings != null && IsCustomMode(settings.AccentColorMode) && + TryParseHexColor(settings.CustomAccentColor, out Color customColor, out _)) + { + ApplyAccentToApplication(customColor); + return; + } + + Color systemColor = GetSystemAccentColor(); + ApplyAccentToApplication(systemColor); + } + + public Color GetCurrentAccentColor() + { + var settings = _settingsService?.Settings; + if (settings != null && IsCustomMode(settings.AccentColorMode) && + TryParseHexColor(settings.CustomAccentColor, out Color customColor, out _)) + { + return customColor; + } + + return GetSystemAccentColor(); + } + + public static bool IsCustomMode(string? mode) => + string.Equals(mode, CustomMode, StringComparison.OrdinalIgnoreCase); + + public static bool TryParseHexColor(string? value, out Color color, out string normalizedHex) + { + color = default; + normalizedHex = string.Empty; + + if (string.IsNullOrWhiteSpace(value)) + { + return false; + } + + string cleaned = value.Trim(); + if (cleaned.StartsWith("#", StringComparison.Ordinal)) + { + cleaned = cleaned.Substring(1); + } + + if (cleaned.Length == 6) + { + if (uint.TryParse(cleaned, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint rgb)) + { + byte r = (byte)((rgb >> 16) & 0xFF); + byte g = (byte)((rgb >> 8) & 0xFF); + byte b = (byte)(rgb & 0xFF); + color = Color.FromArgb(0xFF, r, g, b); + normalizedHex = $"#{r:X2}{g:X2}{b:X2}"; + return true; + } + } + else if (cleaned.Length == 8) + { + if (uint.TryParse(cleaned, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint argb)) + { + byte a = (byte)((argb >> 24) & 0xFF); + byte r = (byte)((argb >> 16) & 0xFF); + byte g = (byte)((argb >> 8) & 0xFF); + byte b = (byte)(argb & 0xFF); + color = Color.FromArgb(a, r, g, b); + normalizedHex = $"#{r:X2}{g:X2}{b:X2}"; + return true; + } + } + + return false; + } + + public static Color Lighten(Color color, float factor) + { + factor = Math.Clamp(factor, 0f, 1f); + byte r = (byte)Math.Clamp(color.R + (255 - color.R) * factor, 0, 255); + byte g = (byte)Math.Clamp(color.G + (255 - color.G) * factor, 0, 255); + byte b = (byte)Math.Clamp(color.B + (255 - color.B) * factor, 0, 255); + return Color.FromArgb(color.A, r, g, b); + } + + public static Color Darken(Color color, float factor) + { + factor = Math.Clamp(factor, 0f, 1f); + byte r = (byte)Math.Clamp(color.R * (1f - factor), 0, 255); + byte g = (byte)Math.Clamp(color.G * (1f - factor), 0, 255); + byte b = (byte)Math.Clamp(color.B * (1f - factor), 0, 255); + return Color.FromArgb(color.A, r, g, b); + } + + private Color GetSystemAccentColor() + { + if (Application.Current != null && + Application.Current.TryGetResource("SystemAccentColor", Application.Current.ActualThemeVariant, out var res) && + res is Color systemColor) + { + return systemColor; + } + + return FallbackSystemAccent; + } + + private void ApplyAccentToApplication(Color color) + { + if (Application.Current == null) + { + return; + } + + var app = Application.Current; + app.Resources["SystemAccentColor"] = color; + app.Resources["SystemAccentColorLight1"] = Lighten(color, 0.15f); + app.Resources["SystemAccentColorLight2"] = Lighten(color, 0.30f); + app.Resources["SystemAccentColorLight3"] = Lighten(color, 0.45f); + app.Resources["SystemAccentColorDark1"] = Darken(color, 0.15f); + app.Resources["SystemAccentColorDark2"] = Darken(color, 0.30f); + app.Resources["SystemAccentColorDark3"] = Darken(color, 0.45f); + + app.Resources["AccentBrush"] = new SolidColorBrush(color); + app.Resources["AccentColorBrush"] = new SolidColorBrush(color); + app.Resources["AccentPrimaryBrush"] = new SolidColorBrush(color); + app.Resources["AccentFillColorDefaultBrush"] = new SolidColorBrush(color); + app.Resources["AccentTextFillColorPrimaryBrush"] = new SolidColorBrush(Lighten(color, 0.25f)); + } + + private void NotifyAccentChanged(Color color) + { + AccentChanged?.Invoke(color); + GlobalAccentChanged?.Invoke(color); + } +} diff --git a/PocketMC.App/Services/AppClipboard.cs b/PocketMC.App/Services/AppClipboard.cs new file mode 100644 index 0000000..5bba40d --- /dev/null +++ b/PocketMC.App/Services/AppClipboard.cs @@ -0,0 +1,96 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Threading; + +namespace PocketMC.App.Services; + +public static class AppClipboard +{ + public static Func>? OverrideHandler { get; set; } + + public static async Task SetTextAsync(string text) + { + if (string.IsNullOrEmpty(text)) + { + return false; + } + + if (OverrideHandler != null) + { + return await OverrideHandler(text); + } + + // 1. Try Avalonia Window Clipboard via UI thread dispatcher + try + { + if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop && desktop.MainWindow?.Clipboard != null) + { + var clipboard = desktop.MainWindow.Clipboard; + await Dispatcher.UIThread.InvokeAsync(async () => + { + await clipboard.SetTextAsync(text); + }); + return true; + } + } + catch + { + // Fall through to OS native fallback + } + + // 2. Linux fallback: wl-copy (Wayland), xclip or xsel (X11) + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + if (await TryRunClipboardCommandAsync("wl-copy", string.Empty, text)) return true; + if (await TryRunClipboardCommandAsync("xclip", "-selection clipboard", text)) return true; + if (await TryRunClipboardCommandAsync("xsel", "-b -i", text)) return true; + } + // 3. macOS fallback: pbcopy + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + if (await TryRunClipboardCommandAsync("pbcopy", string.Empty, text)) return true; + } + + return false; + } + + private static async Task TryRunClipboardCommandAsync(string command, string arguments, string input) + { + try + { + using var proc = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = command, + Arguments = arguments, + RedirectStandardInput = true, + RedirectStandardOutput = false, + RedirectStandardError = false, + UseShellExecute = false, + CreateNoWindow = true + } + }; + + if (!proc.Start()) + { + return false; + } + + await proc.StandardInput.WriteAsync(input); + await proc.StandardInput.FlushAsync(); + proc.StandardInput.Close(); + + await proc.WaitForExitAsync(); + return proc.ExitCode == 0; + } + catch + { + return false; + } + } +} diff --git a/PocketMC.App/Services/AvaloniaDialogService.cs b/PocketMC.App/Services/AvaloniaDialogService.cs new file mode 100644 index 0000000..c6e6d2f --- /dev/null +++ b/PocketMC.App/Services/AvaloniaDialogService.cs @@ -0,0 +1,241 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Platform.Storage; +using Avalonia.Threading; +using PocketMC.App.Views.Dialogs; +using PocketMC.Core.Services; + +namespace PocketMC.App.Services; + +public sealed class AvaloniaDialogService : IDialogService +{ + private static Window? GetActiveWindow() + { + if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + { + return desktop.Windows.FirstOrDefault(w => w.IsActive) ?? desktop.MainWindow; + } + + return null; + } + + public async Task ShowDialogAsync( + string title, + string message, + DialogType type = DialogType.Information, + bool showCancel = false, + string? primaryButtonText = null, + string? secondaryButtonText = null, + string? cancelButtonText = null, + string? linkText = null, + string? linkUrl = null) + { + return await Dispatcher.UIThread.InvokeAsync(async () => + { + var owner = GetActiveWindow(); + var dialog = new AppDialogWindow(); + dialog.Configure( + title, + message, + type, + showCancel, + primaryButtonText, + secondaryButtonText, + cancelButtonText, + linkText, + linkUrl); + + if (owner != null) + { + return await dialog.ShowDialog(owner); + } + + dialog.Show(); + return dialog.Result; + }); + } + + public void ShowMessage(string title, string message, DialogType type = DialogType.Information) + { + _ = ShowDialogAsync(title, message, type); + } + + public async Task OpenFolderDialogAsync(string title) + { + return await Dispatcher.UIThread.InvokeAsync(async () => + { + var owner = GetActiveWindow(); + if (owner == null) return null; + + var topLevel = TopLevel.GetTopLevel(owner); + if (topLevel?.StorageProvider == null) return null; + + var result = await topLevel.StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions + { + Title = title, + AllowMultiple = false + }); + + return result.Count > 0 ? result[0].Path.LocalPath : null; + }); + } + + public async Task OpenFileDialogAsync(string title, string filter = "All Files (*.*)|*.*") + { + var files = await OpenFilesDialogAsync(title, filter); + return files.Length > 0 ? files[0] : null; + } + + public async Task OpenFilesDialogAsync(string title, string filter = "All Files (*.*)|*.*") + { + return await Dispatcher.UIThread.InvokeAsync(async () => + { + var owner = GetActiveWindow(); + if (owner == null) return Array.Empty(); + + var topLevel = TopLevel.GetTopLevel(owner); + if (topLevel?.StorageProvider == null) return Array.Empty(); + + var fileTypes = ParseFilterToFileTypeChoices(filter); + + var result = await topLevel.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions + { + Title = title, + AllowMultiple = true, + FileTypeFilter = fileTypes + }); + + return result.Select(f => f.Path.LocalPath).ToArray(); + }); + } + + public async Task<(string? Username, string? Password)> PromptCredentialsAsync( + string title, + string message, + bool askUsername, + bool askPassword) + { + return await Dispatcher.UIThread.InvokeAsync(async () => + { + var owner = GetActiveWindow(); + var dialog = new PasswordPromptDialogWindow(); + dialog.Configure(title, message, askUsername, askPassword); + + if (owner != null) + { + return await dialog.ShowDialog<(string?, string?)>(owner); + } + + return (null, null); + }); + } + + public async Task ShowProgressDialogAsync(string title, string message, Func, Task> action) + { + await Dispatcher.UIThread.InvokeAsync(async () => + { + var owner = GetActiveWindow(); + var cts = new CancellationTokenSource(); + var dialog = new ProgressDialogWindow(); + dialog.Configure(title, message, cts); + + var progress = new Progress(value => dialog.UpdateProgress(value)); + + var workerTask = Task.Run(async () => + { + try + { + await action(progress); + } + finally + { + await Dispatcher.UIThread.InvokeAsync(dialog.Close); + } + }); + + if (owner != null) + { + await dialog.ShowDialog(owner); + } + else + { + dialog.Show(); + } + + await workerTask; + }); + } + + public async Task ShowProgressDialogAsync(string title, string message, Func, Task> action) + { + await Dispatcher.UIThread.InvokeAsync(async () => + { + var owner = GetActiveWindow(); + var cts = new CancellationTokenSource(); + var dialog = new ProgressDialogWindow(); + dialog.Configure(title, message, cts); + + var progress = new Progress(update => dialog.UpdateProgress(update)); + + var workerTask = Task.Run(async () => + { + try + { + await action(progress); + } + finally + { + await Dispatcher.UIThread.InvokeAsync(dialog.Close); + } + }); + + if (owner != null) + { + await dialog.ShowDialog(owner); + } + else + { + dialog.Show(); + } + + await workerTask; + }); + } + + private static List ParseFilterToFileTypeChoices(string filter) + { + var list = new List(); + if (string.IsNullOrWhiteSpace(filter)) + { + return list; + } + + var parts = filter.Split('|', StringSplitOptions.RemoveEmptyEntries); + for (int i = 0; i < parts.Length - 1; i += 2) + { + string name = parts[i].Trim(); + string pattern = parts[i + 1].Trim(); + + var extensions = pattern + .Split(';', StringSplitOptions.RemoveEmptyEntries) + .Select(p => p.Trim().TrimStart('*', '.')) + .Where(ext => !string.IsNullOrEmpty(ext) && ext != "*") + .Select(ext => $"*.{ext}") + .ToList(); + + if (extensions.Count > 0) + { + list.Add(new FilePickerFileType(name) { Patterns = extensions }); + } + } + + return list; + } +} diff --git a/PocketMC.App/Services/Console/ConsoleLogFilter.cs b/PocketMC.App/Services/Console/ConsoleLogFilter.cs new file mode 100644 index 0000000..2d204db --- /dev/null +++ b/PocketMC.App/Services/Console/ConsoleLogFilter.cs @@ -0,0 +1,51 @@ +using System; +using System.Text.RegularExpressions; + +namespace PocketMC.App.Services.Console; + +public static class ConsoleLogFilter +{ + private static readonly TimeSpan RegexTimeout = TimeSpan.FromMilliseconds(250); + + public static bool MatchesSearch(string line, string? query, bool useRegex = false) + { + if (string.IsNullOrWhiteSpace(query)) + { + return true; + } + + if (useRegex) + { + try + { + return Regex.IsMatch( + line, + query, + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, + RegexTimeout); + } + catch (Exception ex) when (ex is ArgumentException or RegexMatchTimeoutException) + { + return false; + } + } + + string[] keywords = query.Split(' ', StringSplitOptions.RemoveEmptyEntries); + foreach (string keyword in keywords) + { + if (keyword.StartsWith('-') && keyword.Length > 1) + { + if (line.Contains(keyword[1..], StringComparison.OrdinalIgnoreCase)) + { + return false; + } + } + else if (!line.Contains(keyword, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + } + + return true; + } +} diff --git a/PocketMC.App/Services/Console/ConsoleLogLevel.cs b/PocketMC.App/Services/Console/ConsoleLogLevel.cs new file mode 100644 index 0000000..ff0a8f0 --- /dev/null +++ b/PocketMC.App/Services/Console/ConsoleLogLevel.cs @@ -0,0 +1,12 @@ +namespace PocketMC.App.Services.Console; + +public enum ConsoleLogLevel +{ + Info = 0, + Warn, + Error, + Debug, + Trace, + Chat, + System +} diff --git a/PocketMC.App/Services/Console/LogLineClassifier.cs b/PocketMC.App/Services/Console/LogLineClassifier.cs new file mode 100644 index 0000000..1d8d1c9 --- /dev/null +++ b/PocketMC.App/Services/Console/LogLineClassifier.cs @@ -0,0 +1,118 @@ +using System; +using System.Text.RegularExpressions; + +namespace PocketMC.App.Services.Console; + +public static class LogLineClassifier +{ + private static readonly TimeSpan RegexTimeout = TimeSpan.FromMilliseconds(250); + + private static readonly Regex ChatOrPlayerEventRegex = new( + @"^\[.*?\](?:\s*\[.*?\])*:\s*(?:<[^>]+>\s.*|[^\s:]+\s(?:joined|left) the game)$", + RegexOptions.Compiled | RegexOptions.CultureInvariant, + RegexTimeout); + + private static readonly Regex LogPrefixRegex = new( + @"^\[.*?\](?:\s*\[.*?\])*:\s*", + RegexOptions.Compiled | RegexOptions.CultureInvariant, + RegexTimeout); + + public static ConsoleLogLevel Classify(string? text, ConsoleLogLevel previousLevel = ConsoleLogLevel.Info) + { + if (string.IsNullOrWhiteSpace(text)) + { + return ConsoleLogLevel.Info; + } + + string trimmed = text.TrimStart(); + if (trimmed.StartsWith("at ", StringComparison.Ordinal) || + trimmed.StartsWith("...", StringComparison.Ordinal) || + text.Contains("Caused by:", StringComparison.Ordinal)) + { + return previousLevel; + } + + if (text.StartsWith("> ", StringComparison.Ordinal)) + { + return ConsoleLogLevel.System; + } + + if (IsChatOrPlayerEvent(text)) + { + return ConsoleLogLevel.Chat; + } + + string searchTarget = text.ToUpperInvariant(); + try + { + Match prefixMatch = LogPrefixRegex.Match(text); + if (prefixMatch.Success) + { + searchTarget = prefixMatch.Value.ToUpperInvariant(); + } + } + catch (RegexMatchTimeoutException) + { + } + + if (ContainsAny(searchTarget, "ERROR", "FATAL", "SEVERE", "CRITICAL", "EXCEPTION")) + { + return ConsoleLogLevel.Error; + } + + if (ContainsAny(searchTarget, "WARN", "****", "***")) + { + return ConsoleLogLevel.Warn; + } + + if (ContainsAny(searchTarget, "DEBUG")) + { + return ConsoleLogLevel.Debug; + } + + if (ContainsAny(searchTarget, "TRACE")) + { + return ConsoleLogLevel.Trace; + } + + return ConsoleLogLevel.Info; + } + + public static string GetHexColor(ConsoleLogLevel level) + { + return level switch + { + ConsoleLogLevel.Error => "#EF4444", // Red + ConsoleLogLevel.Warn => "#F59E0B", // Yellow/Amber + ConsoleLogLevel.Chat => "#10B981", // Green + ConsoleLogLevel.System => "#8B5CF6", // Purple/Indigo + ConsoleLogLevel.Debug => "#60A5FA", // Blue + ConsoleLogLevel.Trace => "#9CA3AF", // Dim Gray + _ => "#E4E4E7" // Off-white default + }; + } + + private static bool IsChatOrPlayerEvent(string text) + { + try + { + return ChatOrPlayerEventRegex.IsMatch(text); + } + catch (RegexMatchTimeoutException) + { + return false; + } + } + + private static bool ContainsAny(string text, params string[] needles) + { + foreach (string needle in needles) + { + if (text.Contains(needle, StringComparison.Ordinal)) + { + return true; + } + } + return false; + } +} diff --git a/PocketMC.App/Services/ImageProcessingService.cs b/PocketMC.App/Services/ImageProcessingService.cs new file mode 100644 index 0000000..71f03da --- /dev/null +++ b/PocketMC.App/Services/ImageProcessingService.cs @@ -0,0 +1,53 @@ +using System; +using System.IO; +using PocketMC.Core.Services; +using SkiaSharp; + +namespace PocketMC.App.Services +{ + public class ImageProcessingService : IImageProcessingService + { + public byte[] CropAndResizeImage(byte[] imageBytes, int pxX, int pxY, int pxSize, int targetSize = 64) + { + if (imageBytes == null || imageBytes.Length == 0) + throw new ArgumentException("Image bytes cannot be empty.", nameof(imageBytes)); + + using var original = SKBitmap.Decode(imageBytes); + if (original == null) + throw new InvalidOperationException("Failed to decode image data."); + + pxX = Math.Clamp(pxX, 0, original.Width); + pxY = Math.Clamp(pxY, 0, original.Height); + if (pxX + pxSize > original.Width) pxSize = original.Width - pxX; + if (pxY + pxSize > original.Height) pxSize = original.Height - pxY; + + if (pxSize <= 0) + throw new InvalidOperationException("Invalid crop region dimensions."); + + var subsetRect = new SKRectI(pxX, pxY, pxX + pxSize, pxY + pxSize); + using var cropped = new SKBitmap(pxSize, pxSize); + if (!original.ExtractSubset(cropped, subsetRect)) + { + throw new InvalidOperationException("Failed to extract image crop subset."); + } + + var resizeInfo = new SKImageInfo(targetSize, targetSize, SKColorType.Rgba8888, SKAlphaType.Premul); + using var resized = cropped.Resize(resizeInfo, SKFilterQuality.High); + if (resized == null) + { + throw new InvalidOperationException("Failed to resize cropped image."); + } + + using var image = SKImage.FromBitmap(resized); + using var data = image.Encode(SKEncodedImageFormat.Png, 100); + return data.ToArray(); + } + + public void CropAndSaveToFile(string inputImagePath, string outputImagePath, int pxX, int pxY, int pxSize, int targetSize = 64) + { + byte[] inputBytes = File.ReadAllBytes(inputImagePath); + byte[] croppedBytes = CropAndResizeImage(inputBytes, pxX, pxY, pxSize, targetSize); + File.WriteAllBytes(outputImagePath, croppedBytes); + } + } +} diff --git a/PocketMC.App/Services/WallpaperBackdropService.cs b/PocketMC.App/Services/WallpaperBackdropService.cs new file mode 100644 index 0000000..dd3ad2c --- /dev/null +++ b/PocketMC.App/Services/WallpaperBackdropService.cs @@ -0,0 +1,186 @@ +using System; +using System.IO; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Media; +using Avalonia.Media.Imaging; +using Avalonia.Platform; +using PocketMC.Core.Services; +using SkiaSharp; + +namespace PocketMC.App.Services; + +public sealed class WallpaperBackdropService : IDisposable +{ + private const string DefaultWallpaperAssetUri = "avares://PocketMC.App/Assets/default_wallpaper.png"; + private readonly ISettingsService? _settingsService; + + private Bitmap? _cachedBlurredBitmap; + private string? _cachedWallpaperPath; + private double _cachedBlurRadius = -1; + + public WallpaperBackdropService(ISettingsService? settingsService = null) + { + _settingsService = settingsService; + } + + public static SolidColorBrush CreateTintBrush(double opacity) + { + byte alpha = (byte)Math.Clamp((int)Math.Round(opacity * 255.0), 0, 255); + return new SolidColorBrush(Color.FromArgb(alpha, 0x18, 0x18, 0x18)); + } + + public void Apply(Image? wallpaperImage, Border? tintOverlay, double blurRadius = 80.0, double tintOpacity = 0.72, string? customPath = null) + { + if (tintOverlay != null) + { + tintOverlay.Background = CreateTintBrush(tintOpacity); + tintOverlay.IsVisible = true; + } + + if (wallpaperImage == null) + { + return; + } + + string effectivePath = customPath ?? _settingsService?.Settings?.CustomBackgroundImagePath ?? string.Empty; + + try + { + if (_cachedBlurredBitmap == null || + _cachedWallpaperPath != effectivePath || + Math.Abs(_cachedBlurRadius - blurRadius) > 0.5) + { + _cachedBlurredBitmap?.Dispose(); + _cachedBlurredBitmap = GenerateBlurredBitmap(effectivePath, blurRadius); + _cachedWallpaperPath = effectivePath; + _cachedBlurRadius = blurRadius; + } + + if (_cachedBlurredBitmap != null) + { + wallpaperImage.Source = _cachedBlurredBitmap; + wallpaperImage.Stretch = Stretch.UniformToFill; + wallpaperImage.IsVisible = true; + } + else + { + wallpaperImage.IsVisible = false; + } + } + catch + { + wallpaperImage.IsVisible = false; + } + } + + public void Detach(Image? wallpaperImage, Border? tintOverlay) + { + if (wallpaperImage != null) + { + wallpaperImage.IsVisible = false; + wallpaperImage.Source = null; + } + + if (tintOverlay != null) + { + tintOverlay.IsVisible = false; + } + } + + public static Bitmap? GenerateBlurredBitmap(string? path, double blurRadius, int maxDimension = 1920) + { + byte[]? bytes = GenerateBlurredImageBytes(path, blurRadius, maxDimension); + if (bytes == null || bytes.Length == 0) + { + return null; + } + + using var ms = new MemoryStream(bytes); + return new Bitmap(ms); + } + + public static byte[]? GenerateBlurredImageBytes(string? path, double blurRadius, int maxDimension = 1920) + { + using var stream = OpenWallpaperStream(path); + if (stream == null) + { + return null; + } + + using var originalSkia = SKBitmap.Decode(stream); + if (originalSkia == null) + { + return null; + } + + int targetWidth = originalSkia.Width; + int targetHeight = originalSkia.Height; + + if (targetWidth > maxDimension || targetHeight > maxDimension) + { + float scale = Math.Min((float)maxDimension / targetWidth, (float)maxDimension / targetHeight); + targetWidth = Math.Max(1, (int)(targetWidth * scale)); + targetHeight = Math.Max(1, (int)(targetHeight * scale)); + } + + using var scaledBitmap = originalSkia.Resize(new SKImageInfo(targetWidth, targetHeight), SKFilterQuality.Medium); + if (scaledBitmap == null) + { + return null; + } + + var blurredBitmap = new SKBitmap(targetWidth, targetHeight, scaledBitmap.ColorType, scaledBitmap.AlphaType); + using (var canvas = new SKCanvas(blurredBitmap)) + { + canvas.Clear(SKColors.Transparent); + float sigma = (float)Math.Max(1.0, blurRadius / 2.0); + using var paint = new SKPaint + { + ImageFilter = SKImageFilter.CreateBlur(sigma, sigma), + IsAntialias = true + }; + canvas.DrawBitmap(scaledBitmap, 0, 0, paint); + } + + using var image = SKImage.FromBitmap(blurredBitmap); + using var data = image.Encode(SKEncodedImageFormat.Png, 90); + return data.ToArray(); + } + + private static Stream? OpenWallpaperStream(string? path) + { + if (!string.IsNullOrWhiteSpace(path) && File.Exists(path)) + { + try + { + return File.OpenRead(path); + } + catch + { + // Fall back to default + } + } + + try + { + var uri = new Uri(DefaultWallpaperAssetUri); + if (AssetLoader.Exists(uri)) + { + return AssetLoader.Open(uri); + } + } + catch + { + // Ignore asset loading error + } + + return null; + } + + public void Dispose() + { + _cachedBlurredBitmap?.Dispose(); + _cachedBlurredBitmap = null; + } +} diff --git a/PocketMC.App/Styles/SkeletonStyles.axaml b/PocketMC.App/Styles/SkeletonStyles.axaml new file mode 100644 index 0000000..8624054 --- /dev/null +++ b/PocketMC.App/Styles/SkeletonStyles.axaml @@ -0,0 +1,43 @@ + + + + + + + + + + + + diff --git a/PocketMC.App/ViewLocator.cs b/PocketMC.App/ViewLocator.cs index e31cdb1..ff1eef5 100755 --- a/PocketMC.App/ViewLocator.cs +++ b/PocketMC.App/ViewLocator.cs @@ -6,33 +6,45 @@ namespace PocketMC.App { public class ViewLocator : IDataTemplate { - public Control? Build(object? data) + public static Type? ResolveViewType(Type vmType) { - if (data is null) return null; - - var vmName = data.GetType().FullName!; + var vmName = vmType.FullName!; var viewName = vmName.Replace(".ViewModels.", ".Views.", StringComparison.Ordinal); var name = viewName.Replace("ViewModel", "View", StringComparison.Ordinal); - var type = Type.GetType(name); + var type = vmType.Assembly.GetType(name) ?? Type.GetType(name); if (type == null) { name = viewName.Replace("ViewModel", "Page", StringComparison.Ordinal); - type = Type.GetType(name); + type = vmType.Assembly.GetType(name) ?? Type.GetType(name); } + return type; + } + + public Control? Build(object? data) + { + if (data is null) return null; + + var type = ResolveViewType(data.GetType()); if (type != null) { - var resolvedView = App.Services.GetService(type); - if (resolvedView is Control control) + Control control; + var resolvedView = App.Services?.GetService(type); + if (resolvedView is Control c) { - return control; + control = c; } - - return (Control)Activator.CreateInstance(type)!; + else + { + control = (Control)Activator.CreateInstance(type)!; + } + + control.DataContext = data; + return control; } - return new TextBlock { Text = "View Not Found: " + name }; + return new TextBlock { Text = "View Not Found: " + data.GetType().FullName }; } public bool Match(object? data) diff --git a/PocketMC.App/ViewModels/AboutViewModel.cs b/PocketMC.App/ViewModels/AboutViewModel.cs index afaf45f..85c69fc 100644 --- a/PocketMC.App/ViewModels/AboutViewModel.cs +++ b/PocketMC.App/ViewModels/AboutViewModel.cs @@ -9,6 +9,9 @@ using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using PocketMC.Core.Services; +using PocketMC.Infrastructure.Configuration; +using PocketMC.Infrastructure.WhatsNew; +using PocketMC.App.Views; namespace PocketMC.App.ViewModels; @@ -16,8 +19,9 @@ public partial class AboutViewModel : ObservableObject { private readonly ISettingsService _settingsService; private readonly IInstanceService _instanceService; + private readonly WhatsNewService? _whatsNewService; - public string AppVersion => "Version 1.0.2 (Linux & macOS Native)"; + public string AppVersion => "Version 1.0.4-beta (Linux & macOS Native)"; [ObservableProperty] private string _currentDataRoot = string.Empty; @@ -26,6 +30,13 @@ public partial class AboutViewModel : ObservableObject private string _changeRootStatus = string.Empty; public IRelayCommand OpenGitHubCommand { get; } + public IRelayCommand OpenWebsiteCommand { get; } + public IRelayCommand OpenStudioCommand { get; } + public IRelayCommand OpenWhatsNewCommand { get; } + public IRelayCommand OpenDivyCommand { get; } + public IRelayCommand OpenSahajCommand { get; } + public IRelayCommand OpenJohndinglesinCommand { get; } + public IRelayCommand OpenNexViceCommand { get; } public IRelayCommand OpenDiscordCommand { get; } public IRelayCommand CopyDiscordInviteCommand { get; } public IRelayCommand OpenInstagramCommand { get; } @@ -37,25 +48,43 @@ public partial class AboutViewModel : ObservableObject public IAsyncRelayCommand ChangeDataRootCommand { get; } public IRelayCommand OpenDataRootFolderCommand { get; } - public AboutViewModel(ISettingsService settingsService, IInstanceService instanceService) + public AboutViewModel(ISettingsService settingsService, IInstanceService instanceService, WhatsNewService? whatsNewService = null) { _settingsService = settingsService; _instanceService = instanceService; + _whatsNewService = whatsNewService; _currentDataRoot = _settingsService.GetDataRoot(); - OpenGitHubCommand = new RelayCommand(() => OpenUrl("https://github.com/PocketMC/pocket-mc-linux-mac")); - OpenDiscordCommand = new RelayCommand(() => OpenUrl("https://discord.gg/pocketmc")); + OpenGitHubCommand = new RelayCommand(() => OpenUrl(AppUrls.GitHub)); + OpenWebsiteCommand = new RelayCommand(() => OpenUrl(AppUrls.Website)); + OpenStudioCommand = new RelayCommand(() => OpenUrl(AppUrls.Studio)); + OpenWhatsNewCommand = new RelayCommand(OpenWhatsNew); + OpenDivyCommand = new RelayCommand(() => OpenUrl(AppUrls.DivyGitHub)); + OpenSahajCommand = new RelayCommand(() => OpenUrl(AppUrls.SahajGitHub)); + OpenJohndinglesinCommand = new RelayCommand(() => OpenUrl(AppUrls.JohndinglesinGitHub)); + OpenNexViceCommand = new RelayCommand(() => OpenUrl(AppUrls.NexViceDiscord)); + OpenDiscordCommand = new RelayCommand(() => OpenUrl(AppUrls.DiscordInvite)); CopyDiscordInviteCommand = new RelayCommand(CopyDiscordInvite); - OpenInstagramCommand = new RelayCommand(() => OpenUrl("https://instagram.com/pocketmc")); - OpenYouTubeCommand = new RelayCommand(() => OpenUrl("https://youtube.com/@pocketmc")); - OpenRedditCommand = new RelayCommand(() => OpenUrl("https://reddit.com/r/pocketmc")); - OpenFeedbackCommand = new RelayCommand(() => OpenUrl("https://github.com/PocketMC/pocket-mc-linux-mac/issues")); - OpenDonationCommand = new RelayCommand(() => OpenUrl("https://buymeacoffee.com/pocketmc")); + OpenInstagramCommand = new RelayCommand(() => OpenUrl(AppUrls.Instagram)); + OpenYouTubeCommand = new RelayCommand(() => OpenUrl(AppUrls.YouTube)); + OpenRedditCommand = new RelayCommand(() => OpenUrl(AppUrls.Reddit)); + OpenFeedbackCommand = new RelayCommand(() => OpenUrl(AppUrls.Feedback)); + OpenDonationCommand = new RelayCommand(() => OpenUrl(AppUrls.Donation)); NavigateBackCommand = new RelayCommand(NavigateBack); ChangeDataRootCommand = new AsyncRelayCommand(ChangeDataRootAsync); OpenDataRootFolderCommand = new RelayCommand(OpenDataRootFolder); } + private void OpenWhatsNew() + { + var whatsNewSvc = _whatsNewService ?? App.Services.GetService(typeof(WhatsNewService)) as WhatsNewService; + if (whatsNewSvc != null && Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop && desktop.MainWindow != null) + { + var win = new WhatsNewWindow(whatsNewSvc); + win.ShowDialog(desktop.MainWindow); + } + } + private async Task ChangeDataRootAsync() { if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop && desktop.MainWindow != null) @@ -132,18 +161,27 @@ private async void CopyDiscordInvite() var topLevel = TopLevel.GetTopLevel(desktop.MainWindow); if (topLevel?.Clipboard != null) { - await topLevel.Clipboard.SetTextAsync("https://discord.gg/pocketmc"); + await topLevel.Clipboard.SetTextAsync(AppUrls.DiscordInvite); } } } private void NavigateBack() { - var mainVM = App.Services.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; - if (mainVM != null) + var navService = App.Services?.GetService(typeof(PocketMC.App.Navigation.IAppNavigationService)) as PocketMC.App.Navigation.IAppNavigationService; + if (navService?.CanNavigateBack == true) + { + navService.NavigateBack(); + } + else if (navService != null) + { + navService.NavigateToDashboard(); + } + else { - var dashVM = App.Services.GetService(typeof(DashboardViewModel)) as DashboardViewModel; - if (dashVM != null) + var mainVM = App.Services?.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; + var dashVM = App.Services?.GetService(typeof(DashboardViewModel)) as DashboardViewModel; + if (mainVM != null && dashVM != null) { mainVM.CurrentViewModel = dashVM; } diff --git a/PocketMC.App/ViewModels/AiDiagnosticViewModel.cs b/PocketMC.App/ViewModels/AiDiagnosticViewModel.cs index 6a312bf..a7b03ad 100755 --- a/PocketMC.App/ViewModels/AiDiagnosticViewModel.cs +++ b/PocketMC.App/ViewModels/AiDiagnosticViewModel.cs @@ -218,13 +218,27 @@ private async Task AnalyzeAsync() private void GoBack() { - if (SelectedInstance == null) return; - var mainVM = App.Services.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; - if (mainVM != null) + var navService = App.Services?.GetService(typeof(PocketMC.App.Navigation.IAppNavigationService)) as PocketMC.App.Navigation.IAppNavigationService; + if (navService?.CanNavigateBack == true) + { + navService.NavigateBack(); + } + else if (navService != null) + { + navService.NavigateToDashboard(); + } + else if (SelectedInstance != null) { - var consoleVM = App.Services.GetRequiredService(); - consoleVM.Initialize(SelectedInstance); - mainVM.CurrentViewModel = consoleVM; + var mainVM = App.Services?.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; + if (mainVM != null) + { + var consoleVM = App.Services?.GetRequiredService(); + if (consoleVM != null) + { + consoleVM.Initialize(SelectedInstance); + mainVM.CurrentViewModel = consoleVM; + } + } } } } diff --git a/PocketMC.App/ViewModels/AppSettingsViewModel.cs b/PocketMC.App/ViewModels/AppSettingsViewModel.cs new file mode 100644 index 0000000..e2f82a5 --- /dev/null +++ b/PocketMC.App/ViewModels/AppSettingsViewModel.cs @@ -0,0 +1,209 @@ +using System; +using System.IO; +using Avalonia.Media; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using PocketMC.App.Services; +using PocketMC.Core.Models; +using PocketMC.Core.Services; +using PocketMC.Infrastructure.Services; + +namespace PocketMC.App.ViewModels; + +public partial class AppSettingsViewModel : ObservableObject +{ + private readonly ISettingsService _settingsService; + private readonly AccentColorService _accentColorService; + private readonly WallpaperBackdropService _wallpaperService; + private readonly SettingsBackupService _backupService; + private readonly IDialogService? _dialogService; + + [ObservableProperty] + private string _accentColorMode = "Custom"; + + [ObservableProperty] + private string _customAccentColor = "#008B00"; + + [ObservableProperty] + private string _windowBackdrop = "BlurredWallpaper"; + + [ObservableProperty] + private double _wallpaperBlurRadius = 80.0; + + [ObservableProperty] + private double _wallpaperTintOpacity = 0.72; + + [ObservableProperty] + private string? _customBackgroundImagePath; + + [ObservableProperty] + private bool _startMinimizedToTray; + + [ObservableProperty] + private bool _minimizeToTrayOnClose; + + [ObservableProperty] + private bool _keepComputerAwakeWhileServersRunning = true; + + [ObservableProperty] + private int _consoleBufferSize = 5000; + + [ObservableProperty] + private bool _enableDiscordRpc = true; + + [ObservableProperty] + private bool _discordRpcShowServerName; + + [ObservableProperty] + private bool _discordRpcShowPlayerCount = true; + + [ObservableProperty] + private bool _discordRpcShowVersion = true; + + [ObservableProperty] + private bool _discordRpcShowUptime = true; + + [ObservableProperty] + private bool _discordRpcShowDownloadButton = true; + + [ObservableProperty] + private string _aiProvider = "Gemini"; + + [ObservableProperty] + private string? _aiApiKey; + + [ObservableProperty] + private string? _aiModel; + + [ObservableProperty] + private string? _aiEndpoint; + + [ObservableProperty] + private bool _enableAiSummarization; + + [ObservableProperty] + private string? _curseForgeApiKey; + + [ObservableProperty] + private string _dataRootPath = string.Empty; + + [ObservableProperty] + private string? _externalBackupDirectory; + + [ObservableProperty] + private string? _statusMessage; + + public AppSettingsViewModel( + ISettingsService settingsService, + AccentColorService accentColorService, + WallpaperBackdropService wallpaperService, + SettingsBackupService backupService, + IDialogService? dialogService = null) + { + _settingsService = settingsService; + _accentColorService = accentColorService; + _wallpaperService = wallpaperService; + _backupService = backupService; + _dialogService = dialogService; + + LoadFromSettings(); + } + + public void LoadFromSettings() + { + var s = _settingsService.Settings; + + AccentColorMode = s.AccentColorMode; + CustomAccentColor = s.CustomAccentColor ?? "#008B00"; + WindowBackdrop = s.WindowBackdrop; + WallpaperBlurRadius = s.WallpaperBlurRadius; + WallpaperTintOpacity = s.WallpaperTintOpacity; + CustomBackgroundImagePath = s.CustomBackgroundImagePath; + + StartMinimizedToTray = s.StartMinimizedToTray; + MinimizeToTrayOnClose = s.MinimizeToTrayOnClose; + KeepComputerAwakeWhileServersRunning = s.KeepComputerAwakeWhileServersRunning; + ConsoleBufferSize = s.ConsoleBufferSize; + + EnableDiscordRpc = s.EnableDiscordRpc; + DiscordRpcShowServerName = s.DiscordRpc.ShowServerName; + DiscordRpcShowPlayerCount = s.DiscordRpc.ShowPlayerCount; + DiscordRpcShowVersion = s.DiscordRpc.ShowVersionAndEngine; + DiscordRpcShowUptime = s.DiscordRpc.ShowUptimeTimer; + DiscordRpcShowDownloadButton = s.DiscordRpc.ShowDownloadButton; + + AiProvider = s.AiProvider; + AiApiKey = s.GetCurrentAiKey(); + AiModel = s.GetCurrentAiModel(); + AiEndpoint = s.GetCurrentAiEndpoint(); + EnableAiSummarization = s.EnableAiSummarization; + + CurseForgeApiKey = s.CurseForgeApiKey; + DataRootPath = _settingsService.GetDataRoot(); + ExternalBackupDirectory = s.ExternalBackupDirectory; + } + + [RelayCommand] + public void SaveSettings() + { + var s = _settingsService.Settings; + + s.AccentColorMode = AccentColorMode; + s.CustomAccentColor = CustomAccentColor; + s.WindowBackdrop = WindowBackdrop; + s.WallpaperBlurRadius = WallpaperBlurRadius; + s.WallpaperTintOpacity = WallpaperTintOpacity; + s.CustomBackgroundImagePath = CustomBackgroundImagePath; + + s.StartMinimizedToTray = StartMinimizedToTray; + s.MinimizeToTrayOnClose = MinimizeToTrayOnClose; + s.KeepComputerAwakeWhileServersRunning = KeepComputerAwakeWhileServersRunning; + s.ConsoleBufferSize = ConsoleBufferSize; + + s.EnableDiscordRpc = EnableDiscordRpc; + s.DiscordRpc.Enabled = EnableDiscordRpc; + s.DiscordRpc.ShowServerName = DiscordRpcShowServerName; + s.DiscordRpc.ShowPlayerCount = DiscordRpcShowPlayerCount; + s.DiscordRpc.ShowVersionAndEngine = DiscordRpcShowVersion; + s.DiscordRpc.ShowUptimeTimer = DiscordRpcShowUptime; + s.DiscordRpc.ShowDownloadButton = DiscordRpcShowDownloadButton; + + s.AiProvider = AiProvider; + s.EnableAiSummarization = EnableAiSummarization; + if (!string.IsNullOrWhiteSpace(AiApiKey)) s.AiApiKeys[AiProvider] = AiApiKey; + if (!string.IsNullOrWhiteSpace(AiModel)) s.AiModels[AiProvider] = AiModel; + if (!string.IsNullOrWhiteSpace(AiEndpoint)) s.AiEndpoints[AiProvider] = AiEndpoint; + + s.CurseForgeApiKey = CurseForgeApiKey; + s.ExternalBackupDirectory = ExternalBackupDirectory; + + _settingsService.Save(); + + // Apply visual updates live + if (AccentColorService.TryParseHexColor(CustomAccentColor, out Color color, out _)) + { + _accentColorService.ApplyCustomAccent(color); + } + + StatusMessage = "Settings saved successfully."; + } + + [RelayCommand] + public void ApplyPresetColor(string hex) + { + CustomAccentColor = hex; + AccentColorMode = "Custom"; + if (AccentColorService.TryParseHexColor(hex, out Color color, out _)) + { + _accentColorService.ApplyCustomAccent(color); + } + SaveSettings(); + } + + [RelayCommand] + public void ResetWallpaper() + { + CustomBackgroundImagePath = null; + SaveSettings(); + } +} diff --git a/PocketMC.App/ViewModels/DashboardActionsViewModel.cs b/PocketMC.App/ViewModels/DashboardActionsViewModel.cs new file mode 100644 index 0000000..ea8900f --- /dev/null +++ b/PocketMC.App/ViewModels/DashboardActionsViewModel.cs @@ -0,0 +1,289 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using Avalonia.Controls.ApplicationLifetimes; +using CommunityToolkit.Mvvm.ComponentModel; +using Microsoft.Extensions.DependencyInjection; +using PocketMC.App.Navigation; +using PocketMC.Core.Models; +using PocketMC.Core.Services; + +namespace PocketMC.App.ViewModels +{ + public partial class DashboardActionsViewModel : ObservableObject + { + private readonly IProcessRunner _processRunner; + private readonly IInstanceService _instanceService; + private readonly IDialogService? _dialogService; + private readonly IAppNavigationService? _navigationService; + private readonly IServiceProvider? _serviceProvider; + private Action? _onOpenSettings; + private Action? _onOpenConsole; + private Action? _onOpenPlayers; + private Action? _onOpenExport; + + public DashboardActionsViewModel( + IProcessRunner processRunner, + IInstanceService instanceService, + IDialogService? dialogService = null, + Action? onOpenSettings = null, + Action? onOpenConsole = null, + Action? onOpenPlayers = null, + Action? onOpenExport = null, + IAppNavigationService? navigationService = null, + IServiceProvider? serviceProvider = null) + { + _processRunner = processRunner; + _instanceService = instanceService; + _dialogService = dialogService; + _onOpenSettings = onOpenSettings; + _onOpenConsole = onOpenConsole; + _onOpenPlayers = onOpenPlayers; + _onOpenExport = onOpenExport; + _navigationService = navigationService; + _serviceProvider = serviceProvider; + } + + public void SetCallbacks( + Action? onOpenSettings = null, + Action? onOpenConsole = null, + Action? onOpenPlayers = null, + Action? onOpenExport = null) + { + if (onOpenSettings != null) _onOpenSettings = onOpenSettings; + if (onOpenConsole != null) _onOpenConsole = onOpenConsole; + if (onOpenPlayers != null) _onOpenPlayers = onOpenPlayers; + if (onOpenExport != null) _onOpenExport = onOpenExport; + } + + public async Task StartServerAsync(InstanceCardViewModel vm) + { + if (vm.IsRunning) return; + + try + { + vm.UpdateState("Starting"); + await _processRunner.StartAsync(vm.Instance); + vm.UpdateState("Online", DateTime.UtcNow); + } + catch (Exception ex) + { + vm.UpdateState("Stopped"); + _dialogService?.ShowMessage("Failed to start server", ex.Message, DialogType.Error); + } + } + + public async Task StopServerAsync(InstanceCardViewModel vm) + { + if (!vm.IsRunning) return; + + try + { + vm.UpdateState("Stopping"); + await _processRunner.StopAsync(vm.Instance); + vm.UpdateState("Stopped"); + } + catch (Exception ex) + { + _dialogService?.ShowMessage("Failed to stop server", ex.Message, DialogType.Error); + } + } + + public async Task RestartServerAsync(InstanceCardViewModel vm) + { + vm.IsWaitingToRestart = true; + try + { + await StopServerAsync(vm); + await Task.Delay(1000); + await StartServerAsync(vm); + } + finally + { + vm.IsWaitingToRestart = false; + } + } + + public async Task DeleteInstanceAsync(InstanceCardViewModel vm) + { + if (vm.IsRunning) + { + _dialogService?.ShowMessage("Cannot Delete", "Please stop the server before deleting it.", DialogType.Warning); + return false; + } + + if (_dialogService != null) + { + var result = await _dialogService.ShowDialogAsync( + "Delete Instance", + $"Are you sure you want to permanently delete instance '{vm.Name}'? This action cannot be undone.", + DialogType.Warning, + showCancel: true, + primaryButtonText: "Delete", + secondaryButtonText: "Cancel"); + + if (result != DialogResult.Ok && result != DialogResult.Yes) + { + return false; + } + } + + await _instanceService.DeleteInstanceAsync(vm.Instance.Slug); + return true; + } + + public async Task TogglePinAsync(InstanceCardViewModel vm) + { + vm.SetPinned(!vm.IsPinned); + await _instanceService.SaveInstanceAsync(vm.Instance); + } + + public void OpenFolder(InstanceCardViewModel vm) + { + string path = vm.Instance.Path; + if (string.IsNullOrEmpty(path) || !Directory.Exists(path)) return; + + try + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + Process.Start(new ProcessStartInfo("explorer.exe", $"\"{path}\"") { UseShellExecute = true }); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + Process.Start("open", $"\"{path}\""); + } + else + { + Process.Start("xdg-open", $"\"{path}\""); + } + } + catch + { + // Fallback or ignore OS launch error + } + } + + public async Task CopyCrashReportAsync(InstanceCardViewModel vm) + { + string crashDir = Path.Combine(vm.Instance.Path, "crash-reports"); + if (!Directory.Exists(crashDir)) + { + _dialogService?.ShowMessage("No Crash Reports", "No crash reports were found for this instance.", DialogType.Information); + return; + } + + var latest = Directory.GetFiles(crashDir, "crash-*.txt") + .OrderByDescending(f => File.GetLastWriteTimeUtc(f)) + .FirstOrDefault(); + + if (latest == null) + { + _dialogService?.ShowMessage("No Crash Reports", "No crash reports found.", DialogType.Information); + return; + } + + string content = await File.ReadAllTextAsync(latest); + if (Avalonia.Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop && desktop.MainWindow?.Clipboard != null) + { + await desktop.MainWindow.Clipboard.SetTextAsync(content); + _dialogService?.ShowMessage("Copied", "Latest crash report copied to clipboard.", DialogType.Information); + } + } + + public void OpenSettings(InstanceCardViewModel vm) + { + if (_onOpenSettings != null) + { + _onOpenSettings.Invoke(vm); + return; + } + + if (_serviceProvider != null && _navigationService != null) + { + var settingsVm = _serviceProvider.GetService(); + if (settingsVm != null) + { + settingsVm.Initialize(vm.Instance); + _navigationService.NavigateToDetailPage( + settingsVm, + $"{vm.Name} Settings", + DetailRouteKind.ServerSettings, + DetailBackNavigation.Dashboard, + clearDetailStack: true); + } + } + } + + public void OpenConsole(InstanceCardViewModel vm) + { + if (_onOpenConsole != null) + { + _onOpenConsole.Invoke(vm); + return; + } + + if (_serviceProvider != null && _navigationService != null) + { + var consoleVm = _serviceProvider.GetService(); + if (consoleVm != null) + { + consoleVm.Initialize(vm.Instance); + _navigationService.NavigateToDetailPage( + consoleVm, + $"{vm.Name} Console", + DetailRouteKind.ServerConsole, + DetailBackNavigation.Dashboard, + clearDetailStack: true); + } + } + } + + public void OpenPlayers(InstanceCardViewModel vm) + { + if (_onOpenPlayers != null) + { + _onOpenPlayers.Invoke(vm); + return; + } + + if (_serviceProvider != null && _navigationService != null) + { + var playersVm = _serviceProvider.GetService(); + if (playersVm != null) + { + playersVm.Initialize(vm.Instance); + _navigationService.NavigateToDetailPage( + playersVm, + $"{vm.Name} Players", + DetailRouteKind.PlayerManagement, + DetailBackNavigation.Dashboard, + clearDetailStack: true); + } + } + } + + public void OpenExport(InstanceCardViewModel vm) + { + if (_onOpenExport != null) + { + _onOpenExport.Invoke(vm); + return; + } + + if (_navigationService != null) + { + var exportVm = new PocketMC.App.ViewModels.Instances.InstanceExportViewModel(vm.Instance, _instanceService, _dialogService); + _navigationService.NavigateToDetailPage( + exportVm, + $"{vm.Name} Export", + DetailRouteKind.InstanceExport, + DetailBackNavigation.Dashboard, + clearDetailStack: true); + } + } + } +} diff --git a/PocketMC.App/ViewModels/DashboardInstanceListViewModel.cs b/PocketMC.App/ViewModels/DashboardInstanceListViewModel.cs new file mode 100644 index 0000000..91f06b6 --- /dev/null +++ b/PocketMC.App/ViewModels/DashboardInstanceListViewModel.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.ObjectModel; +using System.Linq; +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.ComponentModel; +using PocketMC.Core.Models; +using PocketMC.Core.Services; + +namespace PocketMC.App.ViewModels +{ + public partial class DashboardInstanceListViewModel : ObservableObject + { + private readonly IInstanceService _instanceService; + + [ObservableProperty] + private bool _isLoading = true; + + public ObservableCollection Instances { get; } = new(); + + public DashboardInstanceListViewModel(IInstanceService instanceService) + { + _instanceService = instanceService; + } + + public async Task LoadInstancesAsync() + { + try + { + if (Instances.Count == 0) + { + IsLoading = true; + } + + var list = await _instanceService.ListInstancesAsync(); + + var sorted = list + .OrderByDescending(m => m.PinnedAt.HasValue) + .ThenBy(m => m.PinnedAt) + .ThenByDescending(m => m.CreatedAt) + .ToList(); + + // Synchronize collection + var currentMap = Instances.ToDictionary(c => c.Id); + var newCards = new ObservableCollection(); + + foreach (var item in sorted) + { + if (currentMap.TryGetValue(item.Id, out var existingCard)) + { + newCards.Add(existingCard); + } + else + { + newCards.Add(new InstanceCardViewModel(item)); + } + } + + Instances.Clear(); + foreach (var card in newCards) + { + Instances.Add(card); + } + } + finally + { + IsLoading = false; + } + } + } +} diff --git a/PocketMC.App/ViewModels/DashboardMetricsViewModel.cs b/PocketMC.App/ViewModels/DashboardMetricsViewModel.cs new file mode 100644 index 0000000..2be9e6f --- /dev/null +++ b/PocketMC.App/ViewModels/DashboardMetricsViewModel.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using CommunityToolkit.Mvvm.ComponentModel; +using PocketMC.Core.Services; +using PocketMC.Infrastructure.Services; + +namespace PocketMC.App.ViewModels +{ + public partial class DashboardMetricsViewModel : ObservableObject + { + private readonly INativeMetricsProvider? _metricsProvider; + private readonly Dictionary> _cpuHistories = new(); + private readonly Dictionary> _ramHistories = new(); + + public DashboardMetricsViewModel(INativeMetricsProvider? metricsProvider = null) + { + _metricsProvider = metricsProvider; + } + + public void ApplyMetrics(InstanceCardViewModel vm, double cpuUsagePercent, double ramUsageMb, int playerCount) + { + if (!vm.IsRunning) + { + vm.CpuText = "· · ·"; + vm.RamText = "· · ·"; + vm.PlayerStatus = "· · ·"; + vm.NotifyUptimeChanged(); + return; + } + + vm.UpdateMetrics(cpuUsagePercent, ramUsageMb, playerCount); + RecordHistory(vm.Id, cpuUsagePercent, ramUsageMb); + } + + public void ApplyLiveMetrics(InstanceCardViewModel vm, int pid, int playerCount = 0) + { + if (!vm.IsRunning || _metricsProvider == null || pid <= 0) + { + vm.CpuText = "· · ·"; + vm.RamText = "· · ·"; + vm.PlayerStatus = "· · ·"; + vm.NotifyUptimeChanged(); + return; + } + + var snapshot = _metricsProvider.GetProcessMetrics(pid); + double ramMb = snapshot.MemoryBytes / (1024.0 * 1024.0); + ApplyMetrics(vm, snapshot.CpuPercent, ramMb, playerCount); + } + + public IEnumerable GetCpuHistory(Guid id) + { + if (_cpuHistories.TryGetValue(id, out var buffer)) + { + return buffer.ToList(); + } + return Array.Empty(); + } + + public IEnumerable GetRamHistory(Guid id) + { + if (_ramHistories.TryGetValue(id, out var buffer)) + { + return buffer.ToList(); + } + return Array.Empty(); + } + + private void RecordHistory(Guid id, double cpu, double ram) + { + if (!_cpuHistories.TryGetValue(id, out var cpuBuf)) + { + cpuBuf = new CircularBuffer(30); + _cpuHistories[id] = cpuBuf; + } + cpuBuf.Add(cpu); + + if (!_ramHistories.TryGetValue(id, out var ramBuf)) + { + ramBuf = new CircularBuffer(30); + _ramHistories[id] = ramBuf; + } + ramBuf.Add(ram); + } + } +} diff --git a/PocketMC.App/ViewModels/DashboardViewModel.cs b/PocketMC.App/ViewModels/DashboardViewModel.cs index c723c4a..d6e4f6f 100755 --- a/PocketMC.App/ViewModels/DashboardViewModel.cs +++ b/PocketMC.App/ViewModels/DashboardViewModel.cs @@ -6,15 +6,19 @@ using System.Linq; using System.Threading.Tasks; using System.Timers; +using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Threading; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using Microsoft.Extensions.DependencyInjection; +using PocketMC.App.Navigation; +using PocketMC.App.Views; using PocketMC.Core.Models; using PocketMC.Core.Services; using PocketMC.Infrastructure.Services; -using PocketMC.RemoteControl.Tunnels; +using PocketMC.Platform.Metrics; using PocketMC.RemoteControl.Services; +using PocketMC.RemoteControl.Tunnels; namespace PocketMC.App.ViewModels { @@ -24,849 +28,366 @@ public partial class DashboardViewModel : ObservableObject, IDisposable private readonly IProcessRunner _processRunner; private readonly IPlayerService _playerService; private readonly ProcessMetricsTracker _metricsTracker; - private readonly ThemeManager _themeManager; + private readonly INativeMetricsProvider _metricsProvider; private readonly PlayitApiClient _playitClient; private readonly LocalNetworkAddressService _localNetworkAddressService; + private readonly ISettingsService _settingsService; + private readonly IDialogService? _dialogService; + private readonly IAppNavigationService? _navigationService; + private readonly IServiceProvider? _serviceProvider; + private readonly IGeyserDetector _geyserDetector; + private readonly ISimpleVoiceChatDetector _voiceChatDetector; private readonly System.Timers.Timer _timer; - private readonly Dictionary> _cpuHistories = new(); - private readonly Dictionary> _ramHistories = new(); - - [ObservableProperty] - private ObservableCollection _instances = new(); - - [ObservableProperty] - [NotifyPropertyChangedFor(nameof(IsSelected))] - [NotifyPropertyChangedFor(nameof(SelectedInstanceName))] - [NotifyPropertyChangedFor(nameof(SelectedInstanceEngineType))] - [NotifyPropertyChangedFor(nameof(SelectedInstanceEngineVersion))] - private ServerInstance? _selectedInstance; - - [ObservableProperty] - [NotifyCanExecuteChangedFor(nameof(StartServerCommand))] - [NotifyCanExecuteChangedFor(nameof(StopServerCommand))] - private string _serverState = "Stopped"; - - [ObservableProperty] - private double _cpuUsagePercent; - - [ObservableProperty] - private string _ramUsageFormatted = "0 MB"; - - [ObservableProperty] - private string _portStatusFormatted = "Offline"; - - [ObservableProperty] - private string _configuredPortFormatted = "Unknown"; - - [ObservableProperty] - private int _onlinePlayersCount; - - [ObservableProperty] - private string _onlinePlayersList = "None"; - - [ObservableProperty] - private string _uptime = "00:00:00"; - - [ObservableProperty] - private IEnumerable _cpuHistory = Enumerable.Repeat(0.0, 30); - - [ObservableProperty] - private IEnumerable _ramHistory = Enumerable.Repeat(0.0, 30); - - [ObservableProperty] - private bool _hasInstances; - - [ObservableProperty] - private string _themeOverride = "System"; - - public string SelectedInstanceName => SelectedInstance?.Name ?? string.Empty; - - public string SelectedInstanceEngineType => SelectedInstance?.EngineType.ToString() ?? string.Empty; - - public string SelectedInstanceEngineVersion => SelectedInstance?.EngineVersion ?? string.Empty; - - [ObservableProperty] - private bool _hasPlayitTunnels; - - [ObservableProperty] - private string? _javaTunnelAddress; - - [ObservableProperty] - private bool _showJavaTunnel; - - [ObservableProperty] - private string? _bedrockTunnelAddress; - - [ObservableProperty] - private bool _showBedrockTunnel; - - [ObservableProperty] - private string? _voiceChatTunnelAddress; - - [ObservableProperty] - private bool _showVoiceChatTunnel; + private List _cachedActiveTunnels = new(); + private int _pollCount = 0; - [ObservableProperty] - private bool _isCreatingTunnels; + public DashboardInstanceListViewModel ListVm { get; } + public DashboardMetricsViewModel MetricsVm { get; } + public DashboardActionsViewModel ActionsVm { get; } - [ObservableProperty] - private string? _lanAddressDisplayText; + public ObservableCollection Instances => ListVm.Instances; + public bool IsLoading => ListVm.IsLoading; + public bool HasInstances => Instances.Count > 0; + public string ServerState => SelectedInstance?.StatusText ?? "Stopped"; - [ObservableProperty] - private bool _hasLanAddress; + public async Task LoadInstancesAsync() + { + await ListVm.LoadInstancesAsync(); + if (SelectedInstance == null && Instances.Count > 0) + { + SelectedInstance = Instances[0]; + } + OnPropertyChanged(nameof(HasInstances)); + OnPropertyChanged(nameof(ServerState)); + } [ObservableProperty] - private bool _showBedrockIp; - - private readonly ISettingsService _settingsService; - private readonly RemoteTunnelManager _tunnelManager; - private List _cachedActiveTunnels = new(); - private int _pollCount = 0; - - public bool IsSelected => SelectedInstance != null; + [NotifyPropertyChangedFor(nameof(ServerState))] + private InstanceCardViewModel? _selectedInstance; + + public IAsyncRelayCommand NewInstanceCommand { get; } + public IAsyncRelayCommand RefreshInstancesCommand { get; } + public IAsyncRelayCommand StartServerCommand { get; } + public IAsyncRelayCommand StopServerCommand { get; } + public IAsyncRelayCommand RestartServerCommand { get; } + public IAsyncRelayCommand DeleteInstanceCommand { get; } + public IRelayCommand OpenFolderCommand { get; } + public IAsyncRelayCommand CopyCrashReportCommand { get; } + public IRelayCommand ExportInstanceCommand { get; } + public IRelayCommand ServerSettingsCommand { get; } + public IRelayCommand OpenConsoleCommand { get; } + public IRelayCommand OpenPlayersCommand { get; } + public IAsyncRelayCommand TogglePinCommand { get; } + public IAsyncRelayCommand CopyIpCommand { get; } + public IAsyncRelayCommand CopyLanIpCommand { get; } + public IAsyncRelayCommand CopyNumericIpCommand { get; } + public IAsyncRelayCommand CopyBedrockIpCommand { get; } public DashboardViewModel( IInstanceService instanceService, IProcessRunner processRunner, IPlayerService playerService, ProcessMetricsTracker metricsTracker, - ThemeManager themeManager, + INativeMetricsProvider metricsProvider, PlayitApiClient playitClient, LocalNetworkAddressService localNetworkAddressService, ISettingsService settingsService, - RemoteTunnelManager tunnelManager) + IDialogService? dialogService = null, + IAppNavigationService? navigationService = null, + IServiceProvider? serviceProvider = null, + DashboardInstanceListViewModel? listVm = null, + DashboardMetricsViewModel? metricsVm = null, + DashboardActionsViewModel? actionsVm = null, + IGeyserDetector? geyserDetector = null, + ISimpleVoiceChatDetector? voiceChatDetector = null) { _instanceService = instanceService; _processRunner = processRunner; _playerService = playerService; _metricsTracker = metricsTracker; - _themeManager = themeManager; + _metricsProvider = metricsProvider; _playitClient = playitClient; _localNetworkAddressService = localNetworkAddressService; _settingsService = settingsService; - _tunnelManager = tunnelManager; - - _processRunner.StateChanged += OnProcessStateChanged; - - _timer = new System.Timers.Timer(2000); - _timer.Elapsed += OnTimerElapsed; - - // Load persisted theme settings - ThemeOverride = _settingsService.Settings.Theme ?? "System"; - var mode = ThemeOverride switch - { - "Light" => ThemeMode.Light, - "Dark" => ThemeMode.Dark, - _ => ThemeMode.System - }; - _themeManager.ApplyTheme(mode); - - // Initial load - _ = LoadInstancesAsync(); - } + _dialogService = dialogService; + _navigationService = navigationService; + _serviceProvider = serviceProvider; + _geyserDetector = geyserDetector ?? new GeyserDetector(new AddonManifestService()); + _voiceChatDetector = voiceChatDetector ?? new SimpleVoiceChatDetector(new AddonManifestService()); - private void OnProcessStateChanged(string slug, string state) - { - if (SelectedInstance != null && SelectedInstance.Slug == slug) - { - Dispatcher.UIThread.Post(() => - { - ServerState = state; - StartServerCommand.NotifyCanExecuteChanged(); - StopServerCommand.NotifyCanExecuteChanged(); - }); - } - } - - public async Task LoadInstancesAsync() - { - var list = await _instanceService.ListInstancesAsync(); - Action updateAction = () => + ListVm = listVm ?? new DashboardInstanceListViewModel(instanceService); + ListVm.PropertyChanged += (s, e) => { - var currentSlug = SelectedInstance?.Slug ?? _settingsService.Settings.LastSelectedInstanceSlug; - - Instances.Clear(); - foreach (var inst in list) + if (e.PropertyName == nameof(DashboardInstanceListViewModel.IsLoading)) { - Instances.Add(inst); - } - HasInstances = Instances.Count > 0; - - ServerInstance? target = null; - if (!string.IsNullOrEmpty(currentSlug)) - { - target = Instances.FirstOrDefault(i => i.Slug == currentSlug); + OnPropertyChanged(nameof(IsLoading)); + OnPropertyChanged(nameof(HasInstances)); } + }; - if (target == null && HasInstances) + MetricsVm = metricsVm ?? new DashboardMetricsViewModel(metricsProvider); + + ActionsVm = actionsVm ?? new DashboardActionsViewModel( + processRunner, + instanceService, + dialogService, + onOpenSettings: NavigateToSettings, + onOpenConsole: NavigateToConsole, + onOpenPlayers: NavigateToPlayers, + onOpenExport: NavigateToExport, + navigationService: _navigationService, + serviceProvider: _serviceProvider); + + ActionsVm.SetCallbacks( + onOpenSettings: NavigateToSettings, + onOpenConsole: NavigateToConsole, + onOpenPlayers: NavigateToPlayers, + onOpenExport: NavigateToExport); + + NewInstanceCommand = new AsyncRelayCommand(NavigateToNewInstance); + RefreshInstancesCommand = new AsyncRelayCommand(async () => await ListVm.LoadInstancesAsync()); + StartServerCommand = new AsyncRelayCommand(async card => { if (card != null) await ActionsVm.StartServerAsync(card); }); + StopServerCommand = new AsyncRelayCommand(async card => { if (card != null) await ActionsVm.StopServerAsync(card); }); + RestartServerCommand = new AsyncRelayCommand(async card => { if (card != null) await ActionsVm.RestartServerAsync(card); }); + DeleteInstanceCommand = new AsyncRelayCommand(async card => + { + if (card != null) { - target = Instances[0]; + bool deleted = await ActionsVm.DeleteInstanceAsync(card); + if (deleted) + { + Instances.Remove(card); + OnPropertyChanged(nameof(HasInstances)); + } } - - SelectedInstance = target; - OnPropertyChanged(nameof(SelectedInstanceName)); - OnPropertyChanged(nameof(SelectedInstanceEngineType)); - OnPropertyChanged(nameof(SelectedInstanceEngineVersion)); - OnPropertyChanged(nameof(IsSelected)); - - if (!_timer.Enabled) + }); + OpenFolderCommand = new RelayCommand(card => { if (card != null) ActionsVm.OpenFolder(card); }); + CopyCrashReportCommand = new AsyncRelayCommand(async card => { if (card != null) await ActionsVm.CopyCrashReportAsync(card); }); + ExportInstanceCommand = new RelayCommand(card => { if (card != null) ActionsVm.OpenExport(card); }); + ServerSettingsCommand = new RelayCommand(card => { if (card != null) ActionsVm.OpenSettings(card); }); + OpenConsoleCommand = new RelayCommand(card => { if (card != null) ActionsVm.OpenConsole(card); }); + OpenPlayersCommand = new RelayCommand(card => { if (card != null) ActionsVm.OpenPlayers(card); }); + TogglePinCommand = new AsyncRelayCommand(async card => + { + if (card != null) { - _timer.Start(); + await ActionsVm.TogglePinAsync(card); + await ListVm.LoadInstancesAsync(); } - }; + }); - if (Dispatcher.UIThread.CheckAccess()) + CopyIpCommand = new AsyncRelayCommand(async card => { - updateAction(); - } - else + if (card?.TunnelAddress != null) await CopyToClipboardAsync(card.TunnelAddress); + }); + CopyLanIpCommand = new AsyncRelayCommand(async card => { - Dispatcher.UIThread.Post(updateAction); - } - } - - partial void OnSelectedInstanceChanged(ServerInstance? value) - { - if (value != null) + if (card?.LanAddressDisplayText != null) await CopyToClipboardAsync(card.LanAddressDisplayText); + }); + CopyNumericIpCommand = new AsyncRelayCommand(async card => { - _settingsService.Settings.LastSelectedInstanceSlug = value.Slug; - _settingsService.Save(); - } - - if (value == null) + if (card?.NumericTunnelAddress != null) await CopyToClipboardAsync(card.NumericTunnelAddress); + }); + CopyBedrockIpCommand = new AsyncRelayCommand(async card => { - ServerState = "Stopped"; - CpuUsagePercent = 0; - RamUsageFormatted = "0 MB"; - PortStatusFormatted = "Offline"; - ConfiguredPortFormatted = "Unknown"; - OnlinePlayersCount = 0; - OnlinePlayersList = "None"; - Uptime = "00:00:00"; - CpuHistory = Enumerable.Repeat(0.0, 30); - RamHistory = Enumerable.Repeat(0.0, 30); - ShowBedrockIp = false; - ShowJavaTunnel = false; - ShowBedrockTunnel = false; - HasPlayitTunnels = false; - HasLanAddress = false; - return; - } + if (card?.BedrockTunnelAddress != null) await CopyToClipboardAsync(card.BedrockTunnelAddress); + }); - // Sync current state - if (_processRunner.TryGetRunningInfo(value.Slug, out _, out string state)) - { - ServerState = state; - } - else - { - ServerState = "Stopped"; - } + _processRunner.StateChanged += OnProcessStateChanged; - // Load histories - CpuHistory = GetOrCreateHistory(_cpuHistories, value.Slug).ToList(); - RamHistory = GetOrCreateHistory(_ramHistories, value.Slug).ToList(); + _timer = new System.Timers.Timer(2000); + _timer.Elapsed += OnTimerElapsed; - StartServerCommand.NotifyCanExecuteChanged(); - StopServerCommand.NotifyCanExecuteChanged(); + _ = InitializeAsync(); + } - // Force poll immediately - _ = PollMetricsAsync(); + private async Task InitializeAsync() + { + await ListVm.LoadInstancesAsync(); + if (SelectedInstance == null && Instances.Count > 0) + { + SelectedInstance = Instances[0]; + } + OnPropertyChanged(nameof(HasInstances)); + OnPropertyChanged(nameof(ServerState)); + _timer.Start(); } - private CircularBuffer GetOrCreateHistory(Dictionary> dict, string slug) + private void OnProcessStateChanged(string slug, string state) { - if (!dict.TryGetValue(slug, out var buffer)) + Dispatcher.UIThread.Post(() => { - buffer = new CircularBuffer(30); - for (int i = 0; i < 30; i++) + var card = Instances.FirstOrDefault(c => c.Instance.Slug == slug); + if (card != null) { - buffer.Add(0.0); + DateTime? sessionStart = _processRunner.GetSessionStartTime(slug); + card.UpdateState(state, sessionStart); + OnPropertyChanged(nameof(ServerState)); } - dict[slug] = buffer; - } - return buffer; + }); } private void OnTimerElapsed(object? sender, ElapsedEventArgs e) { - _ = PollMetricsAsync(); + _ = PollDashboardStateAsync(); } - private async Task PollMetricsAsync() + private async Task PollDashboardStateAsync() { - var selected = SelectedInstance; - if (selected == null) return; - - // Query process run info - bool isRunning = _processRunner.TryGetRunningInfo(selected.Slug, out int pgid, out string state); - - double cpu = 0.0; - long ramBytes = 0; - bool portListens = false; - int playerCount = 0; - string playerList = "None"; - string uptimeStr = "00:00:00"; - - // Port checking - int port = GetServerPort(selected); - bool isUdp = (selected.EngineType == EngineType.PocketMine || selected.EngineType == EngineType.Bedrock); - - // Check for geyser presence (Geyser*.jar in plugins or mods) - bool hasGeyser = false; - bool isJava = selected.EngineType != EngineType.Bedrock && selected.EngineType != EngineType.PocketMine; - if (isJava) - { - string pluginsDir = Path.Combine(selected.Path, "plugins"); - string modsDir = Path.Combine(selected.Path, "mods"); - hasGeyser = (Directory.Exists(pluginsDir) && Directory.GetFiles(pluginsDir, "Geyser*.jar").Any()) || - (Directory.Exists(modsDir) && Directory.GetFiles(modsDir, "Geyser*.jar").Any()); - } - - bool showBedrock = selected.EngineType == EngineType.Bedrock || selected.EngineType == EngineType.PocketMine || hasGeyser; - bool showJava = isJava; - - if (isRunning && pgid > 0) - { - try - { - // CPU and Memory - var metrics = _metricsTracker.GetGroupMetrics(pgid); - cpu = metrics.CpuPercentage; - ramBytes = metrics.MemoryBytes; - - portListens = PortProber.IsPortListening(port, isUdp); - - // Online players - var players = await _playerService.GetOnlinePlayersAsync(selected); - if (players != null && players.Count > 0) - { - playerCount = players.Count; - playerList = string.Join(", ", players); - } - - // Uptime - using var proc = Process.GetProcessById(pgid); - if (proc != null && !proc.HasExited) - { - var diff = DateTime.UtcNow - proc.StartTime.ToUniversalTime(); - uptimeStr = $"{(int)diff.TotalHours:D2}:{diff.Minutes:D2}:{diff.Seconds:D2}"; - } - } - catch - { - // Process exited during query - } - } - - // Sync Tunnels data (throttled to avoid HTTP 429 rate limits) _pollCount++; + + // Throttled tunnel sync string? playitSecret = _settingsService.Settings.PlayitPartnerConnection?.SecretKey; - if (!string.IsNullOrEmpty(playitSecret) && (_cachedActiveTunnels == null || _cachedActiveTunnels.Count == 0 || _pollCount % 15 == 1)) + if (!string.IsNullOrEmpty(playitSecret) && (_cachedActiveTunnels.Count == 0 || _pollCount % 15 == 1)) { try { var response = await _playitClient.GetTunnelsAsync(); - if (response != null && response.Success && response.Tunnels != null) + if (response?.Success == true && response.Tunnels != null) { _cachedActiveTunnels = response.Tunnels.Where(t => t.IsEnabled).ToList(); } } - catch { /* Ignore API errors during polling */ } + catch { /* Ignore API errors during background polling */ } } - List activeTunnels = _cachedActiveTunnels ?? new(); - - // Update Histories - var cpuBuf = GetOrCreateHistory(_cpuHistories, selected.Slug); - cpuBuf.Add(cpu); - var cpuList = cpuBuf.ToList(); - var ramBuf = GetOrCreateHistory(_ramHistories, selected.Slug); - double totalMemory = GC.GetGCMemoryInfo().TotalAvailableMemoryBytes; - if (totalMemory <= 0) totalMemory = 16.0 * 1024 * 1024 * 1024; - double ramPercent = ((double)ramBytes / totalMemory) * 100.0; - ramPercent = Math.Clamp(ramPercent, 0, 100); - ramBuf.Add(ramPercent); - var ramList = ramBuf.ToList(); - - Dispatcher.UIThread.Post(() => + foreach (var card in Instances.ToList()) { - // Double check selection hasn't changed - if (SelectedInstance?.Slug == selected.Slug) + bool isRunning = _processRunner.TryGetRunningInfo(card.Instance.Slug, out int pgid, out string state); + if (isRunning && pgid > 0) { - ServerState = state; - CpuUsagePercent = Math.Round(cpu, 1); - RamUsageFormatted = FormatBytes(ramBytes); - PortStatusFormatted = portListens ? "Listening" : "Offline"; - ConfiguredPortFormatted = $"{GetServerPort(selected)} ({(selected.EngineType == EngineType.PocketMine || selected.EngineType == EngineType.Bedrock ? "UDP" : "TCP")})"; - OnlinePlayersCount = playerCount; - OnlinePlayersList = playerList; - Uptime = uptimeStr; - CpuHistory = cpuList; - RamHistory = ramList; - - // IP Setup - ShowBedrockIp = showBedrock; - - if (activeTunnels.Count > 0) - { - HasPlayitTunnels = true; - if (showJava) - { - var javaTunnel = activeTunnels.FirstOrDefault(t => t.TunnelType == "minecraft-java" && t.Port == port); - if (javaTunnel != null) - { - JavaTunnelAddress = javaTunnel.PublicAddress; - ShowJavaTunnel = true; - } - else - { - ShowJavaTunnel = false; - } - } - else - { - ShowJavaTunnel = false; - } - - if (showBedrock) - { - var bedrockTunnel = activeTunnels.FirstOrDefault(t => t.TunnelType == "minecraft-bedrock"); - if (bedrockTunnel != null) - { - BedrockTunnelAddress = bedrockTunnel.PublicAddress; - ShowBedrockTunnel = true; - } - else - { - ShowBedrockTunnel = false; - } - } - else - { - ShowBedrockTunnel = false; - } - - var voiceTunnel = activeTunnels.FirstOrDefault(t => t.TunnelType == "mc-simple-voice-chat" || (t.TunnelType != null && t.TunnelType.Contains("voice"))); - if (voiceTunnel != null) - { - VoiceChatTunnelAddress = voiceTunnel.PublicAddress; - ShowVoiceChatTunnel = true; - } - else - { - ShowVoiceChatTunnel = false; - } - } - else - { - HasPlayitTunnels = false; - ShowJavaTunnel = false; - ShowBedrockTunnel = false; - ShowVoiceChatTunnel = false; - } - - // Lan IP - if (isRunning) + int playerCount = 0; + try { - HasLanAddress = true; - var ips = _localNetworkAddressService.GetLocalIPv4Addresses().ToList(); - if (ips.Count > 0) - { - LanAddressDisplayText = $"{ips.First()}:{port}"; - } - else - { - LanAddressDisplayText = $"127.0.0.1:{port}"; - } + var players = await _playerService.GetOnlinePlayersAsync(card.Instance); + playerCount = players?.Count ?? 0; } - else + catch { /* Process might be starting or stopping */ } + + MetricsVm.ApplyLiveMetrics(card, pgid, playerCount); + + // Sync tunnels + string? javaTunnel = null; + string? numericTunnel = null; + string? bedrockTunnel = null; + string? bedrockNumericTunnel = null; + string? lanAddress = null; + + int port = card.Instance.ServerPort ?? 25565; + var localIp = _localNetworkAddressService.GetLocalIPv4Addresses().FirstOrDefault(); + if (!string.IsNullOrEmpty(localIp)) { - HasLanAddress = false; + lanAddress = $"{localIp}:{port}"; } - } - }); - } - private string FormatBytes(long bytes) - { - if (bytes == 0) return "0 MB"; - double mb = bytes / (1024.0 * 1024.0); - return $"{mb:F1} MB"; - } - - private int GetServerPort(ServerInstance instance) - { - string propPath = Path.Combine(instance.Path, "server.properties"); - if (File.Exists(propPath)) - { - try - { - var lines = File.ReadAllLines(propPath); - foreach (var line in lines) + if (_cachedActiveTunnels.Count > 0) { - if (line.StartsWith("server-port=")) + var match = _cachedActiveTunnels.FirstOrDefault(t => t.Port == port); + if (match != null) { - if (int.TryParse(line.Split('=')[1].Trim(), out int port)) - { - return port; - } + javaTunnel = match.PublicAddress; + numericTunnel = match.NumericAddress; } } - } - catch { } - } - return (instance.EngineType == EngineType.PocketMine || instance.EngineType == EngineType.Bedrock) ? 19132 : 25565; - } - [RelayCommand(CanExecute = nameof(CanStart))] - private async Task StartServerAsync() - { - if (SelectedInstance != null) - { - await _processRunner.StartAsync(SelectedInstance); - - // Auto create / verify Playit tunnels on server start - if (_playitClient.HasPartnerConnection()) - { - _ = CreateOrToggleTunnelsAsync(); + card.UpdateTunnels(javaTunnel, numericTunnel, bedrockTunnel, bedrockNumericTunnel, lanAddress); } else { - bool promptConnect = await PocketMC.App.Views.ConfirmationDialogWindow.ShowAsync( - "Playit.gg Remote Tunnel", - "Would you like to connect your Playit.gg account to automatically expose this server to the internet?", - "Connect Account"); - - if (promptConnect) - { - var wizard = new PocketMC.App.Views.PlayitSetupWizardWindow - { - DataContext = new PlayitSetupWizardViewModel() - }; - - if (Avalonia.Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop && desktop.MainWindow != null) - { - await wizard.ShowDialog(desktop.MainWindow); - if (_playitClient.HasPartnerConnection()) - { - _ = CreateOrToggleTunnelsAsync(); - } - } - } + card.NotifyUptimeChanged(); } } } - private bool CanStart() => SelectedInstance != null && (ServerState == "Stopped" || ServerState == "Crashed"); - - [RelayCommand(CanExecute = nameof(CanStop))] - private async Task StopServerAsync() - { - if (SelectedInstance != null) - { - await _processRunner.StopAsync(SelectedInstance); - } - } - - private bool CanStop() => SelectedInstance != null && ServerState == "Running"; - - [RelayCommand] - private async Task DeleteServerAsync() - { - if (SelectedInstance != null) - { - var target = SelectedInstance; - bool confirmed = await PocketMC.App.Views.ConfirmationDialogWindow.ShowAsync( - "Delete Server Instance", - $"Are you sure you want to delete server instance '{target.Name}'?\nAll world data, configs, and installed plugins will be deleted permanently.", - "Delete Server"); - - if (!confirmed) return; - - await _instanceService.DeleteInstanceAsync(target.Slug); - SelectedInstance = null; - await LoadInstancesAsync(); - } - } - - [RelayCommand] - private void ToggleTheme() - { - if (ThemeOverride == "System") - { - ThemeOverride = "Light"; - _themeManager.ApplyTheme(ThemeMode.Light); - } - else if (ThemeOverride == "Light") - { - ThemeOverride = "Dark"; - _themeManager.ApplyTheme(ThemeMode.Dark); - } - else - { - ThemeOverride = "System"; - _themeManager.ApplyTheme(ThemeMode.System); - } - - _settingsService.Settings.Theme = ThemeOverride; - _settingsService.Save(); - } - - [RelayCommand] - private void NavigateToNewInstance() - { - var mainVM = App.Services.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; - if (mainVM != null) - { - mainVM.CurrentViewModel = App.Services.GetRequiredService(); - } - } - - [RelayCommand] - private void NavigateToConsole() - { - if (SelectedInstance == null) return; - var mainVM = App.Services.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; - if (mainVM != null) - { - var consoleVM = App.Services.GetRequiredService(); - consoleVM.Initialize(SelectedInstance); - mainVM.CurrentViewModel = consoleVM; - } - } - - [RelayCommand] - private void NavigateToSettings() - { - if (SelectedInstance == null) return; - var mainVM = App.Services.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; - if (mainVM != null) - { - var settingsVM = App.Services.GetRequiredService(); - settingsVM.Initialize(SelectedInstance); - mainVM.CurrentViewModel = settingsVM; - } - } - - [RelayCommand] - private void NavigateToPlayers() - { - if (SelectedInstance == null) return; - var mainVM = App.Services.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; - if (mainVM != null) - { - var playersVM = App.Services.GetRequiredService(); - playersVM.Initialize(SelectedInstance); - mainVM.CurrentViewModel = playersVM; - } - } - - [RelayCommand] - private void NavigateToMarketplace() - { - if (SelectedInstance == null) return; - var mainVM = App.Services.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; - if (mainVM != null) - { - var marketplaceVM = App.Services.GetRequiredService(); - marketplaceVM.Initialize(SelectedInstance); - mainVM.CurrentViewModel = marketplaceVM; - } - } - - [RelayCommand] - private void NavigateToBackups() + private Task NavigateToNewInstance() { - if (SelectedInstance == null) return; - var mainVM = App.Services.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; - if (mainVM != null) - { - var backupsVM = App.Services.GetRequiredService(); - backupsVM.Initialize(SelectedInstance); - mainVM.CurrentViewModel = backupsVM; - } + if (_serviceProvider == null || _navigationService == null) return Task.CompletedTask; + var vm = _serviceProvider.GetRequiredService(); + _navigationService.NavigateToDetailPage( + vm, + "New Instance", + DetailRouteKind.NewInstance, + DetailBackNavigation.Dashboard); + return Task.CompletedTask; } - [RelayCommand] - private void NavigateToTunnels() + private void NavigateToSettings(InstanceCardViewModel card) { - var mainVM = App.Services.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; - if (mainVM != null) - { - var tunnelsVM = App.Services.GetRequiredService(); - _ = tunnelsVM.RefreshAllAsync(); - mainVM.CurrentViewModel = tunnelsVM; - } + if (_serviceProvider == null || _navigationService == null) return; + var vm = _serviceProvider.GetRequiredService(); + vm.Initialize(card.Instance); + _navigationService.NavigateToDetailPage( + vm, + $"{card.Name} Settings", + DetailRouteKind.ServerSettings, + DetailBackNavigation.Dashboard, + clearDetailStack: true); } - [RelayCommand] - private void NavigateToRemoteControl() + private void NavigateToConsole(InstanceCardViewModel card) { - var mainVM = App.Services.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; - if (mainVM != null) - { - mainVM.CurrentViewModel = App.Services.GetRequiredService(); - } + if (_serviceProvider == null || _navigationService == null) return; + var vm = _serviceProvider.GetRequiredService(); + vm.Initialize(card.Instance); + _navigationService.NavigateToDetailPage( + vm, + $"{card.Name} Console", + DetailRouteKind.ServerConsole, + DetailBackNavigation.Dashboard, + clearDetailStack: true); } - [RelayCommand] - private void NavigateToJavaManagement() + private void NavigateToPlayers(InstanceCardViewModel card) { - var mainVM = App.Services.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; - if (mainVM != null) - { - mainVM.CurrentViewModel = App.Services.GetRequiredService(); - } + if (_serviceProvider == null || _navigationService == null) return; + var vm = _serviceProvider.GetRequiredService(); + vm.Initialize(card.Instance); + _navigationService.NavigateToDetailPage( + vm, + $"{card.Name} Players", + DetailRouteKind.PlayerManagement, + DetailBackNavigation.Dashboard, + clearDetailStack: true); } - [RelayCommand] - private void NavigateToAbout() + private void NavigateToExport(InstanceCardViewModel card) { - var mainVM = App.Services.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; - if (mainVM != null) - { - mainVM.CurrentViewModel = App.Services.GetRequiredService(); - } + if (_serviceProvider == null || _navigationService == null) return; + var vm = new PocketMC.App.ViewModels.Instances.InstanceExportViewModel(card.Instance, _instanceService, _dialogService); + _navigationService.NavigateToDetailPage( + vm, + $"{card.Name} Export", + Navigation.DetailRouteKind.InstanceExport, + Navigation.DetailBackNavigation.Dashboard, + clearDetailStack: true); } [RelayCommand] - private async Task CopyAddressAsync(string? address) + public void NavigateToImport() { - if (string.IsNullOrWhiteSpace(address)) return; - if (Avalonia.Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop && desktop.MainWindow != null) - { - var topLevel = Avalonia.Controls.TopLevel.GetTopLevel(desktop.MainWindow); - if (topLevel?.Clipboard != null) - { - await topLevel.Clipboard.SetTextAsync(address); - } - } + if (_serviceProvider == null || _navigationService == null) return; + var vm = new PocketMC.App.ViewModels.Instances.InstanceImportViewModel(_instanceService, _dialogService); + _navigationService.NavigateToDetailPage( + vm, + "Import Instance", + Navigation.DetailRouteKind.InstanceImport, + Navigation.DetailBackNavigation.Dashboard); } - [RelayCommand] - private void OpenFolder(ServerInstance? instance) + private static async Task CopyToClipboardAsync(string text) { - var target = instance ?? SelectedInstance; - if (target != null && Directory.Exists(target.Path)) - { - try - { - Process.Start(new ProcessStartInfo - { - FileName = OperatingSystem.IsMacOS() ? "open" : "xdg-open", - Arguments = target.Path, - UseShellExecute = true - }); - } - catch - { - try - { - Process.Start(OperatingSystem.IsMacOS() ? "open" : "xdg-open", target.Path); - } - catch { } - } - } - } - - [RelayCommand] - private async Task CreateOrToggleTunnelsAsync() - { - if (SelectedInstance == null) return; - var selected = SelectedInstance; - - bool isLinked = _playitClient.HasPartnerConnection(); - if (!isLinked) - { - var wizard = new PocketMC.App.Views.PlayitSetupWizardWindow - { - DataContext = new PlayitSetupWizardViewModel() - }; - - if (Avalonia.Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop && desktop.MainWindow != null) - { - await wizard.ShowDialog(desktop.MainWindow); - isLinked = _playitClient.HasPartnerConnection(); - } - - if (!isLinked) return; - } - - IsCreatingTunnels = true; - try - { - await _tunnelManager.StartTunnelAsync("playit-https"); - await _playitClient.EnsureAgentIdAsync(); - - // Fetch existing tunnels to prevent duplicates - var listResponse = await _playitClient.GetTunnelsAsync(); - var existingTunnels = listResponse?.Tunnels ?? new List(); - - int port = GetServerPort(selected); - bool isJava = selected.EngineType != EngineType.Bedrock && selected.EngineType != EngineType.PocketMine; - - bool HasTunnel(string type, int p) - { - return existingTunnels.Any(t => - string.Equals(t.TunnelType, type, StringComparison.OrdinalIgnoreCase) && - (t.Port == p || t.Name?.Equals($"{selected.Name}-{(type.Contains("java") ? "java" : "bedrock")}", StringComparison.OrdinalIgnoreCase) == true)); - } - - // 1. Create Java or Bedrock tunnel if not present - if (isJava) - { - if (!HasTunnel("minecraft-java", port)) - { - await _playitClient.CreateTunnelAsync($"{selected.Name}-java", "minecraft-java", port); - } - } - else - { - if (!HasTunnel("minecraft-bedrock", port)) - { - await _playitClient.CreateTunnelAsync($"{selected.Name}-bedrock", "minecraft-bedrock", port); - } - } - - // 2. Check for Geyser if Java server - if (isJava) - { - string pluginsDir = Path.Combine(selected.Path, "plugins"); - string modsDir = Path.Combine(selected.Path, "mods"); - bool hasGeyser = (Directory.Exists(pluginsDir) && Directory.GetFiles(pluginsDir, "*Geyser*.jar", SearchOption.TopDirectoryOnly).Any()) || - (Directory.Exists(modsDir) && Directory.GetFiles(modsDir, "*Geyser*.jar", SearchOption.TopDirectoryOnly).Any()); - if (hasGeyser && !HasTunnel("minecraft-bedrock", 19132)) - { - await _playitClient.CreateTunnelAsync($"{selected.Name}-bedrock", "minecraft-bedrock", 19132); - } - - // 3. Check for Simple Voice Chat - bool hasVoiceChat = (Directory.Exists(pluginsDir) && Directory.GetFiles(pluginsDir, "*voice*chat*.jar", SearchOption.AllDirectories).Any()) || - (Directory.Exists(modsDir) && Directory.GetFiles(modsDir, "*voice*chat*.jar", SearchOption.AllDirectories).Any()); - if (hasVoiceChat && !HasTunnel("mc-simple-voice-chat", 24454)) - { - await _playitClient.CreateTunnelAsync($"{selected.Name}-voicechat", "mc-simple-voice-chat", 24454); - } - } - - _cachedActiveTunnels.Clear(); - _pollCount = 0; - await PollMetricsAsync(); - } - catch { } - finally + if (Avalonia.Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop && desktop.MainWindow?.Clipboard != null) { - IsCreatingTunnels = false; + await desktop.MainWindow.Clipboard.SetTextAsync(text); } } public void Dispose() { + _timer.Stop(); _timer.Dispose(); _processRunner.StateChanged -= OnProcessStateChanged; - GC.SuppressFinalize(this); } } } diff --git a/PocketMC.App/ViewModels/InstanceCardViewModel.cs b/PocketMC.App/ViewModels/InstanceCardViewModel.cs new file mode 100644 index 0000000..05cfdf0 --- /dev/null +++ b/PocketMC.App/ViewModels/InstanceCardViewModel.cs @@ -0,0 +1,270 @@ +using System; +using System.Globalization; +using CommunityToolkit.Mvvm.ComponentModel; +using PocketMC.Core.Models; + +namespace PocketMC.App.ViewModels +{ + public partial class InstanceCardViewModel : ObservableObject + { + private ServerInstance _instance; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(IsRunning))] + [NotifyPropertyChangedFor(nameof(IsBusy))] + [NotifyPropertyChangedFor(nameof(ShowRunningControls))] + [NotifyPropertyChangedFor(nameof(ShowStoppedControls))] + [NotifyPropertyChangedFor(nameof(StatusBrush))] + [NotifyPropertyChangedFor(nameof(LastPlayedLabelText))] + [NotifyPropertyChangedFor(nameof(LastPlayedValueText))] + private string _statusText = "Stopped"; + + [ObservableProperty] + private string _cpuText = "· · ·"; + + [ObservableProperty] + private string _ramText = "· · ·"; + + [ObservableProperty] + private string _playerStatus = "· · ·"; + + [ObservableProperty] + private string _uptime = "00:00:00"; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(ShowRunningControls))] + [NotifyPropertyChangedFor(nameof(ShowStoppedControls))] + [NotifyPropertyChangedFor(nameof(StopButtonText))] + private bool _isWaitingToRestart; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(HasTunnelAddress))] + private string? _tunnelAddress; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(HasNumericTunnelAddress))] + private string? _numericTunnelAddress; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(HasBedrockTunnelAddress))] + [NotifyPropertyChangedFor(nameof(ShowBedrockIp))] + private string? _bedrockTunnelAddress; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(HasBedrockNumericTunnelAddress))] + private string? _bedrockNumericTunnelAddress; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(HasLanAddress))] + private string? _lanAddressDisplayText; + + [ObservableProperty] + private bool _isTunnelResolving; + + private DateTime? _sessionStartTime; + + public InstanceCardViewModel(ServerInstance instance) + { + _instance = instance; + } + + public ServerInstance Instance => _instance; + public Guid Id => _instance.Id; + public string Name => _instance.Name; + public string Slug => _instance.Slug; + public string Description => _instance.Description; + public bool IsPinned => _instance.PinnedAt.HasValue; + public string MinecraftVersion => _instance.EngineVersion; + public string ServerType => _instance.EngineType.ToString(); + public int MaxPlayers => _instance.MaxPlayers; + public int MaxRamMb => _instance.MaxRamMb; + + public bool IsRunning => + string.Equals(StatusText, "Online", StringComparison.OrdinalIgnoreCase) || + string.Equals(StatusText, "Running", StringComparison.OrdinalIgnoreCase) || + string.Equals(StatusText, "Starting", StringComparison.OrdinalIgnoreCase) || + string.Equals(StatusText, "SettingUp", StringComparison.OrdinalIgnoreCase) || + string.Equals(StatusText, "Installing", StringComparison.OrdinalIgnoreCase) || + string.Equals(StatusText, "Stopping", StringComparison.OrdinalIgnoreCase); + + public bool IsBusy => + string.Equals(StatusText, "Starting", StringComparison.OrdinalIgnoreCase) || + string.Equals(StatusText, "SettingUp", StringComparison.OrdinalIgnoreCase) || + string.Equals(StatusText, "Installing", StringComparison.OrdinalIgnoreCase) || + string.Equals(StatusText, "Stopping", StringComparison.OrdinalIgnoreCase); + + public bool ShowRunningControls => IsRunning || IsWaitingToRestart; + public bool ShowStoppedControls => !ShowRunningControls; + public string StopButtonText => IsWaitingToRestart ? "Abort" : "Stop"; + + public string StatusBrush => StatusText switch + { + "Online" or "Running" => "#10b981", // Emerald green + "Starting" or "SettingUp" or "Installing" => "#f59e0b", // Amber + "Stopping" or "Crashed" => "#ef4444", // Red + _ => "#9ca3af" // Muted gray + }; + + public string LastPlayedLabelText => IsRunning ? "Uptime" : "Last played"; + + public string LastPlayedValueText + { + get + { + if (IsRunning) + { + if (_sessionStartTime.HasValue) + { + var elapsed = DateTime.UtcNow - _sessionStartTime.Value; + return FormatUptime(elapsed); + } + return "Just started"; + } + + return _instance.LastPlayedAt.HasValue + ? FormatRelativeTime(_instance.LastPlayedAt.Value) + : "Never"; + } + } + + public string LastPlayedTooltip + { + get + { + if (IsRunning && _sessionStartTime.HasValue) + { + return $"Started at: {_sessionStartTime.Value.ToLocalTime().ToString("MMM d, yyyy h:mm tt", CultureInfo.CurrentCulture)}"; + } + + return _instance.LastPlayedAt.HasValue + ? _instance.LastPlayedAt.Value.ToLocalTime().ToString("MMM d, yyyy h:mm tt", CultureInfo.CurrentCulture) + : "Never played"; + } + } + + public string CreatedValueText => _instance.CreatedAt.ToLocalTime().ToString("MMM d, yyyy", CultureInfo.CurrentCulture); + + public string PlatformSummaryText => _instance.EngineType switch + { + EngineType.Bedrock or EngineType.PocketMine => "Bedrock", + _ => "Java" + }; + + public bool IsBedrockServer => _instance.EngineType == EngineType.Bedrock || _instance.EngineType == EngineType.PocketMine; + public bool ShowBedrockIp => IsBedrockServer || HasBedrockTunnelAddress; + + public bool ShowCrossPlayBadge => _showCrossPlayBadge; + private bool _showCrossPlayBadge; + public string CrossPlayBadgeText => "Cross-play"; + public string CrossPlayBadgeTooltip => "Java and Bedrock players can join through Geyser/Floodgate."; + + public bool ShowVoiceChatBadge => _showVoiceChatBadge; + private bool _showVoiceChatBadge; + public string VoiceChatBadgeTooltip => "Simple Voice Chat is configured on this server."; + + public void SetBadges(bool crossPlay, bool voiceChat) + { + _showCrossPlayBadge = crossPlay; + _showVoiceChatBadge = voiceChat; + OnPropertyChanged(nameof(ShowCrossPlayBadge)); + OnPropertyChanged(nameof(ShowVoiceChatBadge)); + } + + public bool HasTunnelAddress => !string.IsNullOrWhiteSpace(TunnelAddress); + public bool HasNumericTunnelAddress => !string.IsNullOrWhiteSpace(NumericTunnelAddress); + public bool HasBedrockTunnelAddress => !string.IsNullOrWhiteSpace(BedrockTunnelAddress); + public bool HasBedrockNumericTunnelAddress => !string.IsNullOrWhiteSpace(BedrockNumericTunnelAddress); + public bool HasLanAddress => !string.IsNullOrWhiteSpace(LanAddressDisplayText); + + public void UpdateState(string newState, DateTime? sessionStart = null) + { + StatusText = newState; + if (sessionStart.HasValue) + { + _sessionStartTime = sessionStart; + } + else if (string.Equals(newState, "Online", StringComparison.OrdinalIgnoreCase) && _sessionStartTime == null) + { + _sessionStartTime = DateTime.UtcNow; + } + else if (string.Equals(newState, "Stopped", StringComparison.OrdinalIgnoreCase) || string.Equals(newState, "Crashed", StringComparison.OrdinalIgnoreCase)) + { + _sessionStartTime = null; + CpuText = "· · ·"; + RamText = "· · ·"; + PlayerStatus = "· · ·"; + _instance.LastPlayedAt = DateTime.UtcNow; + } + + NotifyUptimeChanged(); + } + + public void UpdateMetrics(double cpuPercent, double ramUsedMb, int playerCount) + { + if (!IsRunning) + { + CpuText = "· · ·"; + RamText = "· · ·"; + PlayerStatus = "· · ·"; + return; + } + + CpuText = $"{Math.Round(cpuPercent):0}%"; + double maxRamGb = _instance.MaxRamMb / 1024.0; + double usedRamGb = ramUsedMb / 1024.0; + RamText = $"{usedRamGb:F1} / {maxRamGb:F0} GB"; + PlayerStatus = $"{playerCount} / {_instance.MaxPlayers}"; + + NotifyUptimeChanged(); + } + + public void UpdateTunnels(string? javaTunnel, string? numericTunnel, string? bedrockTunnel, string? bedrockNumericTunnel, string? lanAddress) + { + TunnelAddress = javaTunnel; + NumericTunnelAddress = numericTunnel; + BedrockTunnelAddress = bedrockTunnel; + BedrockNumericTunnelAddress = bedrockNumericTunnel; + LanAddressDisplayText = lanAddress; + } + + public void NotifyUptimeChanged() + { + OnPropertyChanged(nameof(LastPlayedValueText)); + OnPropertyChanged(nameof(LastPlayedTooltip)); + if (_sessionStartTime.HasValue) + { + var elapsed = DateTime.UtcNow - _sessionStartTime.Value; + Uptime = FormatUptime(elapsed); + } + } + + public void SetPinned(bool pinned) + { + _instance.PinnedAt = pinned ? DateTime.UtcNow : null; + OnPropertyChanged(nameof(IsPinned)); + } + + private static string FormatUptime(TimeSpan span) + { + if (span.TotalDays >= 1) + { + return $"{(int)span.TotalDays}d {span.Hours}h {span.Minutes}m"; + } + if (span.TotalHours >= 1) + { + return $"{(int)span.TotalHours}h {span.Minutes}m {span.Seconds}s"; + } + return $"{span.Minutes:D2}:{span.Seconds:D2}"; + } + + private static string FormatRelativeTime(DateTime pastUtc) + { + var diff = DateTime.UtcNow - pastUtc; + if (diff.TotalMinutes < 1) return "Just now"; + if (diff.TotalHours < 1) return $"{(int)diff.TotalMinutes}m ago"; + if (diff.TotalDays < 1) return $"{(int)diff.TotalHours}h ago"; + if (diff.TotalDays < 30) return $"{(int)diff.TotalDays}d ago"; + return pastUtc.ToLocalTime().ToString("MMM d, yyyy", CultureInfo.CurrentCulture); + } + } +} diff --git a/PocketMC.App/ViewModels/Instances/InstanceExportViewModel.cs b/PocketMC.App/ViewModels/Instances/InstanceExportViewModel.cs new file mode 100644 index 0000000..7e6a3c2 --- /dev/null +++ b/PocketMC.App/ViewModels/Instances/InstanceExportViewModel.cs @@ -0,0 +1,121 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using PocketMC.Core.Models; +using PocketMC.Core.Services; + +namespace PocketMC.App.ViewModels.Instances +{ + public partial class InstanceExportViewModel : ObservableObject + { + private readonly ServerInstance _instance; + private readonly IInstanceService _instanceService; + private readonly IDialogService? _dialogService; + + [ObservableProperty] private string _destinationZipPath = string.Empty; + [ObservableProperty] private bool _includeWorlds = true; + [ObservableProperty] private bool _includeSensitiveConfiguration; + [ObservableProperty] private string _currentStep = "Choose export location."; + [ObservableProperty] private double _overallProgress; + [ObservableProperty] private bool _isExporting; + [ObservableProperty] private bool _isComplete; + [ObservableProperty] private bool _hasError; + [ObservableProperty] private string? _errorMessage; + + public ServerInstance Instance => _instance; + public string InstanceName => _instance.Name; + public string ServerType => _instance.EngineType.ToString(); + public string MinecraftVersion => _instance.EngineVersion; + public string ServerSummary => $"{ServerType} - {MinecraftVersion}"; + + public IAsyncRelayCommand ExportCommand { get; } + public IAsyncRelayCommand BrowseDestinationCommand { get; } + public IRelayCommand GoBackCommand { get; } + + public InstanceExportViewModel( + ServerInstance instance, + IInstanceService instanceService, + IDialogService? dialogService = null) + { + _instance = instance; + _instanceService = instanceService; + _dialogService = dialogService; + + string safeName = string.Join("_", instance.Name.Split(Path.GetInvalidFileNameChars())); + string defaultDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + DestinationZipPath = Path.Combine(defaultDir, $"{safeName}-export.zip"); + + ExportCommand = new AsyncRelayCommand(ExportAsync, () => !IsExporting); + BrowseDestinationCommand = new AsyncRelayCommand(BrowseDestinationAsync); + GoBackCommand = new RelayCommand(GoBack); + } + + public async Task BrowseDestinationAsync() + { + if (_dialogService == null) return; + + var folder = await _dialogService.OpenFolderDialogAsync("Select Destination Folder"); + if (!string.IsNullOrEmpty(folder) && Directory.Exists(folder)) + { + string safeName = string.Join("_", _instance.Name.Split(Path.GetInvalidFileNameChars())); + DestinationZipPath = Path.Combine(folder, $"{safeName}-export.zip"); + } + } + + public async Task ExportAsync() + { + if (string.IsNullOrWhiteSpace(DestinationZipPath) || IsExporting) return; + + IsExporting = true; + HasError = false; + ErrorMessage = null; + IsComplete = false; + CurrentStep = "Packaging instance archive..."; + OverallProgress = 30; + + try + { + string? destDir = Path.GetDirectoryName(DestinationZipPath); + if (!string.IsNullOrEmpty(destDir) && !Directory.Exists(destDir)) + { + Directory.CreateDirectory(destDir); + } + + OverallProgress = 60; + await _instanceService.ExportInstanceAsync(_instance.Slug, DestinationZipPath); + + OverallProgress = 100; + CurrentStep = $"Successfully exported to {Path.GetFileName(DestinationZipPath)}"; + IsComplete = true; + + _dialogService?.ShowMessage("Export Complete", $"Instance successfully exported to:\n{DestinationZipPath}", DialogType.Information); + } + catch (Exception ex) + { + HasError = true; + ErrorMessage = ex.Message; + CurrentStep = "Export failed."; + _dialogService?.ShowMessage("Export Failed", ex.Message, DialogType.Error); + } + finally + { + IsExporting = false; + } + } + + private void GoBack() + { + var mainVM = App.Services?.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; + if (mainVM != null) + { + var dashVM = App.Services?.GetService(typeof(DashboardViewModel)) as DashboardViewModel; + if (dashVM != null) + { + mainVM.CurrentViewModel = dashVM; + } + } + } + } +} diff --git a/PocketMC.App/ViewModels/Instances/InstanceImportViewModel.cs b/PocketMC.App/ViewModels/Instances/InstanceImportViewModel.cs new file mode 100644 index 0000000..5bd66f4 --- /dev/null +++ b/PocketMC.App/ViewModels/Instances/InstanceImportViewModel.cs @@ -0,0 +1,159 @@ +using System; +using System.IO; +using System.IO.Compression; +using System.Text.Json; +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using PocketMC.Core.Models; +using PocketMC.Core.Services; + +namespace PocketMC.App.ViewModels.Instances +{ + public partial class InstanceImportViewModel : ObservableObject + { + private readonly IInstanceService _instanceService; + private readonly IDialogService? _dialogService; + + [ObservableProperty] private string _zipPath = string.Empty; + [ObservableProperty] private string _requestedName = string.Empty; + [ObservableProperty] private string _currentStep = "Choose an export ZIP package to import."; + [ObservableProperty] private double _overallProgress; + [ObservableProperty] private bool _isImporting; + [ObservableProperty] private bool _isComplete; + [ObservableProperty] private bool _hasError; + [ObservableProperty] private string? _errorMessage; + [ObservableProperty] private string? _detectedEngineType; + [ObservableProperty] private string? _detectedVersion; + + public bool CanImport => !string.IsNullOrWhiteSpace(ZipPath) && File.Exists(ZipPath) && !string.IsNullOrWhiteSpace(RequestedName) && !IsImporting; + + public IAsyncRelayCommand ImportCommand { get; } + public IAsyncRelayCommand BrowseZipCommand { get; } + public IRelayCommand GoBackCommand { get; } + + public InstanceImportViewModel( + IInstanceService instanceService, + IDialogService? dialogService = null) + { + _instanceService = instanceService; + _dialogService = dialogService; + + ImportCommand = new AsyncRelayCommand(ImportAsync, () => CanImport); + BrowseZipCommand = new AsyncRelayCommand(BrowseZipAsync); + GoBackCommand = new RelayCommand(GoBack); + } + + public async Task BrowseZipAsync() + { + if (_dialogService == null) return; + + var file = await _dialogService.OpenFileDialogAsync("Select PocketMC Export Package", "ZIP Archives (*.zip)|*.zip|All Files (*.*)|*.*"); + if (!string.IsNullOrEmpty(file) && File.Exists(file)) + { + ZipPath = file; + InspectZipPackage(file); + } + } + + private void InspectZipPackage(string path) + { + try + { + using var archive = ZipFile.OpenRead(path); + var manifestEntry = archive.GetEntry(InstanceExportManifest.ManifestFileName); + if (manifestEntry != null) + { + using var reader = new StreamReader(manifestEntry.Open()); + var json = reader.ReadToEnd(); + var manifest = JsonSerializer.Deserialize(json); + if (manifest != null) + { + if (string.IsNullOrWhiteSpace(RequestedName)) + { + RequestedName = manifest.ServerMeta.Name; + } + DetectedEngineType = manifest.Software.Type; + DetectedVersion = manifest.Software.MinecraftVersion; + CurrentStep = $"Detected: {DetectedEngineType} ({DetectedVersion})"; + return; + } + } + + // Fallback to filename as requested name + if (string.IsNullOrWhiteSpace(RequestedName)) + { + RequestedName = Path.GetFileNameWithoutExtension(path).Replace("-export", ""); + } + CurrentStep = "Ready to import."; + } + catch (Exception ex) + { + CurrentStep = $"Warning: Could not read manifest: {ex.Message}"; + } + } + + public async Task ImportAsync() + { + if (!CanImport) return; + + IsImporting = true; + HasError = false; + ErrorMessage = null; + IsComplete = false; + CurrentStep = "Extracting and importing instance..."; + OverallProgress = 20; + + try + { + OverallProgress = 50; + var instance = await _instanceService.ImportInstanceAsync(ZipPath, RequestedName); + + OverallProgress = 100; + CurrentStep = $"Successfully imported '{instance.Name}'!"; + IsComplete = true; + + _dialogService?.ShowMessage("Import Complete", $"Instance '{instance.Name}' imported successfully.", DialogType.Information); + } + catch (Exception ex) + { + HasError = true; + ErrorMessage = ex.Message; + CurrentStep = "Import failed."; + _dialogService?.ShowMessage("Import Failed", ex.Message, DialogType.Error); + } + finally + { + IsImporting = false; + } + } + + private void GoBack() + { + var mainVM = App.Services?.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; + if (mainVM != null) + { + var dashVM = App.Services?.GetService(typeof(DashboardViewModel)) as DashboardViewModel; + if (dashVM != null) + { + mainVM.CurrentViewModel = dashVM; + } + } + } + + partial void OnZipPathChanged(string value) + { + ImportCommand.NotifyCanExecuteChanged(); + } + + partial void OnRequestedNameChanged(string value) + { + ImportCommand.NotifyCanExecuteChanged(); + } + + partial void OnIsImportingChanged(bool value) + { + ImportCommand.NotifyCanExecuteChanged(); + } + } +} diff --git a/PocketMC.App/ViewModels/JavaManagementViewModel.cs b/PocketMC.App/ViewModels/JavaManagementViewModel.cs index 18feb79..454ca98 100644 --- a/PocketMC.App/ViewModels/JavaManagementViewModel.cs +++ b/PocketMC.App/ViewModels/JavaManagementViewModel.cs @@ -229,11 +229,20 @@ private async Task AddCustomRuntimeAsync() private void NavigateBack() { - var mainVM = App.Services.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; - if (mainVM != null) + var navService = App.Services?.GetService(typeof(PocketMC.App.Navigation.IAppNavigationService)) as PocketMC.App.Navigation.IAppNavigationService; + if (navService?.CanNavigateBack == true) { - var dashVM = App.Services.GetService(typeof(DashboardViewModel)) as DashboardViewModel; - if (dashVM != null) + navService.NavigateBack(); + } + else if (navService != null) + { + navService.NavigateToDashboard(); + } + else + { + var mainVM = App.Services?.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; + var dashVM = App.Services?.GetService(typeof(DashboardViewModel)) as DashboardViewModel; + if (mainVM != null && dashVM != null) { mainVM.CurrentViewModel = dashVM; } diff --git a/PocketMC.App/ViewModels/MainWindowViewModel.cs b/PocketMC.App/ViewModels/MainWindowViewModel.cs index 5a6988a..62fa7bd 100755 --- a/PocketMC.App/ViewModels/MainWindowViewModel.cs +++ b/PocketMC.App/ViewModels/MainWindowViewModel.cs @@ -1,15 +1,293 @@ +using System; using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using PocketMC.App.Navigation; +using PocketMC.Core.Services; -namespace PocketMC.App.ViewModels +namespace PocketMC.App.ViewModels; + +public partial class MainWindowViewModel : ObservableObject, IShellHost { - public partial class MainWindowViewModel : ObservableObject + private readonly IAppNavigationService _navigationService; + private readonly IServiceProvider _serviceProvider; + private readonly ISettingsService _settingsService; + private readonly INativeMetricsProvider? _metricsProvider; + private readonly System.Timers.Timer? _metricsTimer; + + [ObservableProperty] + private object _currentViewModel; + + [ObservableProperty] + private string _currentBreadcrumb = "Dashboard"; + + [ObservableProperty] + private bool _canNavigateBack; + + [ObservableProperty] + private bool _canNavigateForward; + + [ObservableProperty] + private string? _titleBarTitle; + + [ObservableProperty] + private string? _titleBarStatusText; + + [ObservableProperty] + private string? _titleBarStatusColor = "#2ECC71"; + + [ObservableProperty] + private bool _isTitleBarContextVisible; + + [ObservableProperty] + private string? _globalHealthStatusText = "System RAM: Calculating..."; + + [ObservableProperty] + private string _globalHealthStatusColor = "#D4D4D8"; + + [ObservableProperty] + private bool _isGlobalHealthVisible = true; + + [ObservableProperty] + private bool _isUpdateBannerVisible; + + [ObservableProperty] + private string? _updateStatusMessage; + + [ObservableProperty] + private bool _isUpdateDownloading; + + [ObservableProperty] + private double _updateDownloadPercent; + + [ObservableProperty] + private bool _isUpdateReadyToApply; + + [ObservableProperty] + private int _unreadNewsCount; + + [ObservableProperty] + private string _selectedNavSection = "Dashboard"; + + public bool IsDashboardSelected => SelectedNavSection == "Dashboard"; + public bool IsTunnelSelected => SelectedNavSection == "Tunnel"; + public bool IsRemoteControlSelected => SelectedNavSection == "RemoteControl"; + public bool IsNewsSelected => SelectedNavSection == "News"; + public bool IsSettingsSelected => SelectedNavSection == "Settings"; + public bool IsRuntimesSelected => SelectedNavSection == "Runtimes"; + public bool IsAboutSelected => SelectedNavSection == "About"; + + partial void OnSelectedNavSectionChanged(string value) + { + OnPropertyChanged(nameof(IsDashboardSelected)); + OnPropertyChanged(nameof(IsTunnelSelected)); + OnPropertyChanged(nameof(IsRemoteControlSelected)); + OnPropertyChanged(nameof(IsNewsSelected)); + OnPropertyChanged(nameof(IsSettingsSelected)); + OnPropertyChanged(nameof(IsRuntimesSelected)); + OnPropertyChanged(nameof(IsAboutSelected)); + } + + public MainWindowViewModel( + IAppNavigationService navigationService, + IServiceProvider serviceProvider, + ISettingsService settingsService, + DashboardViewModel dashboardViewModel, + INativeMetricsProvider? metricsProvider = null) { - [ObservableProperty] - private ObservableObject _currentViewModel; + _navigationService = navigationService; + _serviceProvider = serviceProvider; + _settingsService = settingsService; + _currentViewModel = dashboardViewModel; + _metricsProvider = metricsProvider ?? serviceProvider.GetService(typeof(INativeMetricsProvider)) as INativeMetricsProvider; - public MainWindowViewModel(DashboardViewModel dashboardViewModel) + _navigationService.Initialize(this); + _navigationService.NavigationChanged += OnNavigationChanged; + _navigationService.NavigateToDetailPage(dashboardViewModel, "Dashboard", DetailRouteKind.Dashboard, DetailBackNavigation.Dashboard, clearDetailStack: true); + + UpdateSystemMemoryMetrics(); + _metricsTimer = new System.Timers.Timer(2500); + _metricsTimer.Elapsed += (s, e) => UpdateSystemMemoryMetrics(); + _metricsTimer.AutoReset = true; + _metricsTimer.Start(); + } + + private void UpdateSystemMemoryMetrics() + { + if (_metricsProvider == null) return; + try + { + var (totalBytes, availBytes) = _metricsProvider.GetSystemMemoryMetrics(); + long usedBytes = Math.Max(0, totalBytes - availBytes); + double usedGb = Math.Round(usedBytes / (1024.0 * 1024.0 * 1024.0), 1); + double totalGb = Math.Round(totalBytes / (1024.0 * 1024.0 * 1024.0), 1); + bool isHighUsage = totalBytes > 0 && ((double)usedBytes / totalBytes) > 0.9; + + Avalonia.Threading.Dispatcher.UIThread.Post(() => + { + GlobalHealthStatusText = $"System RAM: {usedGb:0.0} / {totalGb:0.0} GB"; + GlobalHealthStatusColor = isHighUsage ? "#C42B1C" : "#D4D4D8"; + }); + } + catch { - _currentViewModel = dashboardViewModel; + // Ignore metrics sampling exception } } + + private void OnNavigationChanged() + { + CanNavigateBack = _navigationService.CanNavigateBack; + CanNavigateForward = _navigationService.CanNavigateForward; + CurrentBreadcrumb = _navigationService.CurrentBreadcrumb ?? "Dashboard"; + + if (_navigationService.CurrentRouteKind.HasValue) + { + var kind = _navigationService.CurrentRouteKind.Value; + SelectedNavSection = kind switch + { + DetailRouteKind.Dashboard => "Dashboard", + DetailRouteKind.Tunnel => "Tunnel", + DetailRouteKind.RemoteControl => "RemoteControl", + DetailRouteKind.News => "News", + DetailRouteKind.Settings => "Settings", + DetailRouteKind.Runtimes => "Runtimes", + DetailRouteKind.About => "About", + _ => SelectedNavSection + }; + } + } + + public void SetContent(object page) + { + CurrentViewModel = page; + } + + public void UpdateBreadcrumb(string breadcrumb) + { + CurrentBreadcrumb = breadcrumb; + } + + public void SetTitleBarContext(string? title, string? subtitle, string? statusDotColor) + { + TitleBarTitle = title; + TitleBarStatusText = subtitle; + TitleBarStatusColor = statusDotColor ?? "#2ECC71"; + IsTitleBarContextVisible = !string.IsNullOrEmpty(title); + } + + [RelayCommand] + public void NavigateDashboard() + { + SelectedNavSection = "Dashboard"; + var vm = (DashboardViewModel)_serviceProvider.GetService(typeof(DashboardViewModel))! ?? (DashboardViewModel)CurrentViewModel; + _navigationService.NavigateToDetailPage(vm, "Dashboard", DetailRouteKind.Dashboard, DetailBackNavigation.Dashboard, clearDetailStack: true); + } + + [RelayCommand] + public void NavigateTunnel() + { + SelectedNavSection = "Tunnel"; + var vm = _serviceProvider.GetService(typeof(TunnelViewModel)); + if (vm != null) + { + _navigationService.NavigateToDetailPage(vm, "Tunnel", DetailRouteKind.Tunnel, DetailBackNavigation.Dashboard, clearDetailStack: true); + } + } + + [RelayCommand] + public void NavigateRemoteControl() + { + SelectedNavSection = "RemoteControl"; + var vm = _serviceProvider.GetService(typeof(RemoteControlViewModel)); + if (vm != null) + { + _navigationService.NavigateToDetailPage(vm, "Remote Control", DetailRouteKind.RemoteControl, DetailBackNavigation.Dashboard, clearDetailStack: true); + } + } + + [RelayCommand] + public void NavigateSettings() + { + SelectedNavSection = "Settings"; + var vm = _serviceProvider.GetService(typeof(AppSettingsViewModel)); + if (vm != null) + { + _navigationService.NavigateToDetailPage(vm, "Settings", DetailRouteKind.Settings, DetailBackNavigation.Dashboard); + } + } + + [RelayCommand] + public void NavigateRuntimes() + { + SelectedNavSection = "Runtimes"; + var vm = _serviceProvider.GetService(typeof(JavaManagementViewModel)); + if (vm != null) + { + _navigationService.NavigateToDetailPage(vm, "Runtimes", DetailRouteKind.Runtimes, DetailBackNavigation.Dashboard); + } + } + + [RelayCommand] + public void NavigateAbout() + { + SelectedNavSection = "About"; + var vm = _serviceProvider.GetService(typeof(AboutViewModel)); + if (vm != null) + { + _navigationService.NavigateToDetailPage(vm, "About", DetailRouteKind.About, DetailBackNavigation.Dashboard); + } + } + + [RelayCommand] + public void NavigateNews() + { + SelectedNavSection = "News"; + var newsVm = (NewsViewModel?)_serviceProvider.GetService(typeof(NewsViewModel)); + if (newsVm != null) + { + _navigationService.NavigateToDetailPage(newsVm, "Community News", DetailRouteKind.News, DetailBackNavigation.Dashboard); + } + else + { + // Fallback: Shows What's New changelog dialog if NewsViewModel is not available + var whatsNewService = (Infrastructure.WhatsNew.WhatsNewService?)_serviceProvider.GetService(typeof(Infrastructure.WhatsNew.WhatsNewService)); + if (whatsNewService != null) + { + var window = new Views.WhatsNewWindow(whatsNewService); + if (Avalonia.Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop && desktop.MainWindow != null) + { + window.ShowDialog(desktop.MainWindow); + } + else + { + window.Show(); + } + } + } + } + + [RelayCommand] + public void RestartAndApplyUpdate() + { + // Dismiss banner and restart application + IsUpdateBannerVisible = false; + } + + [RelayCommand] + public void DismissUpdateBanner() + { + IsUpdateBannerVisible = false; + } + + [RelayCommand] + public void NavigateBack() + { + _navigationService.NavigateBack(); + } + + [RelayCommand] + public void NavigateForward() + { + _navigationService.NavigateForward(); + } } diff --git a/PocketMC.App/ViewModels/MarketplaceViewModel.cs b/PocketMC.App/ViewModels/MarketplaceViewModel.cs index 866e17d..fa719a4 100755 --- a/PocketMC.App/ViewModels/MarketplaceViewModel.cs +++ b/PocketMC.App/ViewModels/MarketplaceViewModel.cs @@ -212,10 +212,22 @@ await Dispatcher.UIThread.InvokeAsync(() => [RelayCommand] private void NavigateBack() { - var mainVM = App.Services.GetService(); - if (mainVM != null) + var navService = App.Services?.GetService(typeof(PocketMC.App.Navigation.IAppNavigationService)) as PocketMC.App.Navigation.IAppNavigationService; + if (navService?.CanNavigateBack == true) { - mainVM.CurrentViewModel = App.Services.GetRequiredService(); + navService.NavigateBack(); + } + else if (navService != null) + { + navService.NavigateToDashboard(); + } + else + { + var mainVM = App.Services?.GetService(); + if (mainVM != null) + { + mainVM.CurrentViewModel = App.Services?.GetRequiredService()!; + } } } diff --git a/PocketMC.App/ViewModels/NewInstanceViewModel.cs b/PocketMC.App/ViewModels/NewInstanceViewModel.cs index 586a5f6..8e43b0f 100755 --- a/PocketMC.App/ViewModels/NewInstanceViewModel.cs +++ b/PocketMC.App/ViewModels/NewInstanceViewModel.cs @@ -13,7 +13,10 @@ using CommunityToolkit.Mvvm.Input; using PocketMC.Core.Models; using PocketMC.Core.Services; +using PocketMC.Infrastructure.Services; +using PocketMC.App.Navigation; using PocketMC.App.Views; +using PocketMC.App.ViewModels.Instances; namespace PocketMC.App.ViewModels { @@ -22,6 +25,7 @@ public partial class NewInstanceViewModel : ObservableValidator private readonly IInstanceService _instanceService; private readonly IJavaService _javaService; private readonly IPHPService _phpService; + private readonly GeyserProvisioningService? _geyserProvisioningService; private string _name = string.Empty; @@ -148,25 +152,80 @@ public string ProgressText public IAsyncRelayCommand CancelCommand { get; } public IAsyncRelayCommand BrowseWorldCommand { get; } public IRelayCommand OpenEulaLinkCommand { get; } + public IAsyncRelayCommand ImportModpackCommand { get; } + public IRelayCommand ImportInstanceCommand { get; } public NewInstanceViewModel( IInstanceService instanceService, IJavaService javaService, - IPHPService phpService) + IPHPService phpService, + GeyserProvisioningService? geyserProvisioningService = null) { _instanceService = instanceService; _javaService = javaService; _phpService = phpService; + _geyserProvisioningService = geyserProvisioningService; CreateInstanceCommand = new AsyncRelayCommand(CreateInstanceAsync, CanCreate); CancelCommand = new AsyncRelayCommand(CancelAsync); BrowseWorldCommand = new AsyncRelayCommand(BrowseWorldAsync); OpenEulaLinkCommand = new RelayCommand(OpenEulaLink); + ImportModpackCommand = new AsyncRelayCommand(ImportModpackAsync); + ImportInstanceCommand = new RelayCommand(ImportInstance); // Initial load _ = LoadVersionsAsync(); } + private async Task ImportModpackAsync() + { + if (Avalonia.Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop && desktop.MainWindow != null) + { + var topLevel = Avalonia.Controls.TopLevel.GetTopLevel(desktop.MainWindow); + if (topLevel != null) + { + var files = await topLevel.StorageProvider.OpenFilePickerAsync(new Avalonia.Platform.Storage.FilePickerOpenOptions + { + Title = "Select Modpack Archive (.mrpack / .zip)", + AllowMultiple = false, + FileTypeFilter = new[] + { + new Avalonia.Platform.Storage.FilePickerFileType("Modpack Archive (*.mrpack, *.zip)") + { + Patterns = new[] { "*.mrpack", "*.zip" } + } + } + }); + + if (files.Count > 0) + { + var file = files[0]; + CustomWorldPath = file.Path.LocalPath; + string baseName = Path.GetFileNameWithoutExtension(file.Path.LocalPath); + if (string.IsNullOrWhiteSpace(Name)) + { + Name = baseName.Replace(" ", "-"); + } + } + } + } + } + + private void ImportInstance() + { + var navService = App.Services?.GetService(typeof(IAppNavigationService)) as IAppNavigationService; + var importVm = new InstanceImportViewModel(_instanceService); + if (navService != null) + { + navService.NavigateToDetailPage(importVm, "Import Instance", DetailRouteKind.InstanceImport, DetailBackNavigation.Dashboard); + } + else if (Avalonia.Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop && desktop.MainWindow?.DataContext is MainWindowViewModel mainVm) + { + mainVm.SetContent(importVm); + mainVm.UpdateBreadcrumb("Import Instance"); + } + } + private async Task BrowseWorldAsync() { if (Avalonia.Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop && desktop.MainWindow != null) @@ -646,21 +705,30 @@ private async Task CreateInstanceAsync() if (SelectedEngine == EngineType.VanillaJava) { - ProgressText = $"Resolving Minecraft {SelectedVersion} download url..."; - Progress = 0.5; - await DownloadVanillaServerJarAsync(SelectedVersion, jarPath); + if (!File.Exists(jarPath)) + { + ProgressText = $"Resolving Minecraft {SelectedVersion} download url..."; + Progress = 0.5; + await DownloadVanillaServerJarAsync(SelectedVersion, jarPath); + } } else if (SelectedEngine == EngineType.Fabric) { - ProgressText = $"Downloading Fabric {SelectedVersion} server jar..."; - Progress = 0.5; - await DownloadFabricServerJarAsync(SelectedVersion, jarPath); + if (!File.Exists(jarPath)) + { + ProgressText = $"Downloading Fabric {SelectedVersion} server jar..."; + Progress = 0.5; + await DownloadFabricServerJarAsync(SelectedVersion, jarPath); + } } else if (SelectedEngine == EngineType.Paper) { - ProgressText = $"Downloading Paper {SelectedVersion} server jar..."; - Progress = 0.5; - await DownloadPaperServerJarAsync(SelectedVersion, jarPath); + if (!File.Exists(jarPath)) + { + ProgressText = $"Downloading Paper {SelectedVersion} server jar..."; + Progress = 0.5; + await DownloadPaperServerJarAsync(SelectedVersion, jarPath); + } } else if (SelectedEngine == EngineType.Forge) { @@ -705,28 +773,25 @@ private async Task CreateInstanceAsync() try { ProgressText = "Downloading Geyser & Floodgate cross-play plugins..."; - using var client = new HttpClient(); - client.DefaultRequestHeaders.Add("User-Agent", "PocketMC-App"); - - if (SelectedEngine == EngineType.Fabric) - { - string modsDir = Path.Combine(targetDir, "mods"); - Directory.CreateDirectory(modsDir); - await DownloadFileWithProgressAsync(client, "https://download.geysermc.org/v2/projects/geyser/versions/latest/builds/latest/downloads/fabric", Path.Combine(modsDir, "Geyser-Fabric.jar"), "Downloading Geyser Fabric mod"); - await DownloadFileWithProgressAsync(client, "https://download.geysermc.org/v2/projects/floodgate/versions/latest/builds/latest/downloads/fabric", Path.Combine(modsDir, "Floodgate-Fabric.jar"), "Downloading Floodgate Fabric mod"); - } - else if (SelectedEngine == EngineType.NeoForge || SelectedEngine == EngineType.Forge) + if (_geyserProvisioningService != null) { - string modsDir = Path.Combine(targetDir, "mods"); - Directory.CreateDirectory(modsDir); - await DownloadFileWithProgressAsync(client, "https://download.geysermc.org/v2/projects/geyser/versions/latest/builds/latest/downloads/neoforge", Path.Combine(modsDir, "Geyser-NeoForge.jar"), "Downloading Geyser NeoForge mod"); + await _geyserProvisioningService.EnsureGeyserSetupAsync( + targetDir, + SelectedEngine.ToString(), + SelectedVersion, + new Progress(p => + { + if (p.TotalBytes > 0) + { + Progress = 0.7 + (p.Percentage / 100.0) * 0.1; + } + })); } else { - string pluginsDir = Path.Combine(targetDir, "plugins"); - Directory.CreateDirectory(pluginsDir); - await DownloadFileWithProgressAsync(client, "https://download.geysermc.org/v2/projects/geyser/versions/latest/builds/latest/downloads/spigot", Path.Combine(pluginsDir, "Geyser-Spigot.jar"), "Downloading Geyser plugin"); - await DownloadFileWithProgressAsync(client, "https://download.geysermc.org/v2/projects/floodgate/versions/latest/builds/latest/downloads/spigot", Path.Combine(pluginsDir, "Floodgate-Spigot.jar"), "Downloading Floodgate plugin"); + var downloader = new DownloaderService(new HttpClient()); + var prov = new GeyserProvisioningService(downloader, new ModrinthService(new HttpClient())); + await prov.EnsureGeyserSetupAsync(targetDir, SelectedEngine.ToString(), SelectedVersion); } } catch (Exception ex) @@ -752,7 +817,10 @@ private async Task CreateInstanceAsync() ProgressText = $"Downloading PocketMine-MP {SelectedVersion} server file..."; Progress = 0.5; string pharPath = Path.Combine(targetDir, "PocketMine-MP.phar"); - await DownloadPocketMinePharAsync(SelectedVersion, pharPath); + if (!File.Exists(pharPath)) + { + await DownloadPocketMinePharAsync(SelectedVersion, pharPath); + } Progress = 0.8; } else if (SelectedEngine == EngineType.Bedrock) @@ -795,9 +863,9 @@ private async Task CreateInstanceAsync() ProgressText = "Created successfully!"; await Task.Delay(1000); - var mainVM = App.Services.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; - var dashVM = App.Services.GetService(typeof(DashboardViewModel)) as DashboardViewModel; - if (mainVM != null && dashVM != null) + var navService = App.Services?.GetService(typeof(IAppNavigationService)) as IAppNavigationService; + var dashVM = App.Services?.GetService(typeof(DashboardViewModel)) as DashboardViewModel; + if (dashVM != null) { await dashVM.LoadInstancesAsync(); var createdInstance = dashVM.Instances.FirstOrDefault(i => string.Equals(i.Name, instance.Name, StringComparison.OrdinalIgnoreCase)) ?? dashVM.Instances.LastOrDefault(); @@ -805,6 +873,14 @@ private async Task CreateInstanceAsync() { dashVM.SelectedInstance = createdInstance; } + } + + if (navService != null) + { + navService.NavigateToDashboard(); + } + else if (App.Services?.GetService(typeof(MainWindowViewModel)) is MainWindowViewModel mainVM && dashVM != null) + { mainVM.CurrentViewModel = dashVM; } } @@ -1304,10 +1380,14 @@ private async Task CancelAsync() catch { } } - var mainVM = App.Services.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; - if (mainVM != null) + var navService = App.Services?.GetService(typeof(IAppNavigationService)) as IAppNavigationService; + if (navService != null) + { + navService.NavigateToDashboard(); + } + else if (App.Services?.GetService(typeof(MainWindowViewModel)) is MainWindowViewModel mainVM) { - var dashVM = App.Services.GetService(typeof(DashboardViewModel)) as DashboardViewModel; + var dashVM = App.Services?.GetService(typeof(DashboardViewModel)) as DashboardViewModel; if (dashVM != null) { mainVM.CurrentViewModel = dashVM; diff --git a/PocketMC.App/ViewModels/NewsViewModel.cs b/PocketMC.App/ViewModels/NewsViewModel.cs new file mode 100644 index 0000000..af89575 --- /dev/null +++ b/PocketMC.App/ViewModels/NewsViewModel.cs @@ -0,0 +1,155 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using PocketMC.App.Navigation; +using PocketMC.Infrastructure.News; + +namespace PocketMC.App.ViewModels +{ + public sealed class NewsItemViewModel : ObservableObject + { + public NewsItem Item { get; } + + public string Id => Item.Metadata.Id; + public string Title => Item.Title; + public string TypeLabel => Item.Metadata.Type.ToString(); + public string PriorityLabel => Item.Metadata.Priority.ToString(); + public string PublishedLabel => Item.Metadata.PublishedUtc.ToString("MMM dd, yyyy"); + public IReadOnlyList Blocks => Item.Blocks; + + private bool _isRead; + public bool IsRead + { + get => _isRead; + set + { + if (SetProperty(ref _isRead, value)) + { + OnPropertyChanged(nameof(UnreadVisibility)); + } + } + } + + public bool UnreadVisibility => !IsRead; + + public NewsItemViewModel(NewsItem item) + { + Item = item; + _isRead = item.Metadata.IsRead; + } + } + + public partial class NewsViewModel : ObservableObject + { + private readonly NewsService _newsService; + private readonly IAppNavigationService? _navigationService; + + [ObservableProperty] + private ObservableCollection _articles = new(); + + [ObservableProperty] + private NewsItemViewModel? _selectedArticle; + + [ObservableProperty] + private bool _isLoading; + + [ObservableProperty] + private string _syncStatusText = string.Empty; + + public bool HasArticles => Articles.Count > 0; + public bool HasSelectedArticle => SelectedArticle != null; + + public IAsyncRelayCommand RefreshCommand { get; } + public IRelayCommand GoBackCommand { get; } + + public NewsViewModel(NewsService newsService, IAppNavigationService? navigationService = null) + { + _newsService = newsService; + _navigationService = navigationService; + + RefreshCommand = new AsyncRelayCommand(RefreshNewsAsync); + GoBackCommand = new RelayCommand(GoBack); + + _newsService.NewsStateChanged += OnNewsStateChanged; + + LoadCachedArticles(); + _ = RefreshNewsAsync(); + } + + partial void OnSelectedArticleChanged(NewsItemViewModel? value) + { + OnPropertyChanged(nameof(HasSelectedArticle)); + if (value != null && !value.IsRead) + { + value.IsRead = true; + _newsService.MarkRead(value.Id); + } + } + + private void OnNewsStateChanged() + { + Avalonia.Threading.Dispatcher.UIThread.Post(() => + { + LoadCachedArticles(); + }); + } + + private void LoadCachedArticles() + { + var cached = _newsService.GetCachedNews(); + Articles.Clear(); + foreach (var item in cached) + { + Articles.Add(new NewsItemViewModel(item)); + } + + if (SelectedArticle == null && Articles.Count > 0) + { + SelectedArticle = Articles[0]; + } + + OnPropertyChanged(nameof(HasArticles)); + OnPropertyChanged(nameof(HasSelectedArticle)); + } + + private async Task RefreshNewsAsync() + { + if (IsLoading) return; + IsLoading = true; + SyncStatusText = "Checking for announcements..."; + + try + { + var result = await _newsService.SyncAsync(); + LoadCachedArticles(); + SyncStatusText = result.Succeeded + ? $"Last checked: {DateTime.Now:t}" + : $"Check failed: {result.ErrorMessage ?? "Network error"}"; + } + catch (Exception ex) + { + SyncStatusText = $"Check failed: {ex.Message}"; + } + finally + { + IsLoading = false; + } + } + + private void GoBack() + { + if (_navigationService?.CanNavigateBack == true) + { + _navigationService.NavigateBack(); + } + else + { + _navigationService?.NavigateToDashboard(); + } + } + } +} diff --git a/PocketMC.App/ViewModels/PlayerManagementViewModel.cs b/PocketMC.App/ViewModels/PlayerManagementViewModel.cs index a6bbdcd..17c2b5f 100755 --- a/PocketMC.App/ViewModels/PlayerManagementViewModel.cs +++ b/PocketMC.App/ViewModels/PlayerManagementViewModel.cs @@ -10,6 +10,7 @@ using CommunityToolkit.Mvvm.Input; using PocketMC.Core.Models; using PocketMC.Core.Services; +using PocketMC.Infrastructure.Services; namespace PocketMC.App.ViewModels { @@ -18,6 +19,8 @@ public partial class PlayerManagementViewModel : ObservableObject, IDisposable private readonly IInstanceService _instanceService; private readonly IPlayerService _playerService; private readonly IProcessRunner _processRunner; + private readonly BanSidecarService _banSidecarService; + private readonly SemaphoreSlim _fileLock = new(1, 1); private FileSystemWatcher? _watcher; @@ -45,11 +48,13 @@ public partial class PlayerManagementViewModel : ObservableObject, IDisposable public PlayerManagementViewModel( IInstanceService instanceService, IPlayerService playerService, - IProcessRunner processRunner) + IProcessRunner processRunner, + BanSidecarService? banSidecarService = null) { _instanceService = instanceService; _playerService = playerService; _processRunner = processRunner; + _banSidecarService = banSidecarService ?? new BanSidecarService(); KickPlayerCommand = new AsyncRelayCommand(KickPlayerAsync); BanPlayerCommand = new AsyncRelayCommand(BanPlayerAsync); @@ -132,46 +137,70 @@ private List LoadBannedPlayers() var banned = new List(); if (SelectedInstance == null) return banned; - var jsonPath = Path.Combine(SelectedInstance.Path, "banned-players.json"); - if (File.Exists(jsonPath)) + _fileLock.Wait(); + try { - try + var jsonPath = Path.Combine(SelectedInstance.Path, "banned-players.json"); + if (File.Exists(jsonPath)) { - var content = File.ReadAllText(jsonPath); - using var doc = JsonDocument.Parse(content); - if (doc.RootElement.ValueKind == JsonValueKind.Array) + try { - foreach (var el in doc.RootElement.EnumerateArray()) + var content = File.ReadAllText(jsonPath); + using var doc = JsonDocument.Parse(content); + if (doc.RootElement.ValueKind == JsonValueKind.Array) { - if (el.TryGetProperty("name", out var nameProp)) + foreach (var el in doc.RootElement.EnumerateArray()) { - banned.Add(nameProp.GetString() ?? ""); + if (el.TryGetProperty("name", out var nameProp)) + { + banned.Add(nameProp.GetString() ?? ""); + } } } } + catch { } } - catch { } - } - var txtPath = Path.Combine(SelectedInstance.Path, "banned-players.txt"); - if (File.Exists(txtPath)) - { - try + var txtPath = Path.Combine(SelectedInstance.Path, "banned-players.txt"); + if (File.Exists(txtPath)) { - var lines = File.ReadAllLines(txtPath); - foreach (var line in lines) + try { - var trimmed = line.Trim(); - if (!string.IsNullOrEmpty(trimmed) && !trimmed.StartsWith("#")) + var lines = File.ReadAllLines(txtPath); + foreach (var line in lines) { - banned.Add(trimmed); + var trimmed = line.Trim(); + if (!string.IsNullOrEmpty(trimmed) && !trimmed.StartsWith("#")) + { + banned.Add(trimmed); + } } } + catch { } } - catch { } - } - return banned.Where(n => !string.IsNullOrEmpty(n)).Distinct().ToList(); + if (SelectedInstance.EngineType == EngineType.Bedrock) + { + try + { + var sidecarBans = _banSidecarService.GetBannedPlayersAsync(SelectedInstance.Path).GetAwaiter().GetResult(); + foreach (var b in sidecarBans) + { + if (!string.IsNullOrWhiteSpace(b.Name)) + { + banned.Add(b.Name); + } + } + } + catch { } + } + + return banned.Where(n => !string.IsNullOrEmpty(n)).Distinct().ToList(); + } + finally + { + _fileLock.Release(); + } } private void SetupWatcher() @@ -231,11 +260,26 @@ private async Task BanPlayerAsync(string? username) if (SelectedInstance != null) { - bool isRunning = _processRunner.TryGetRunningInfo(SelectedInstance.Slug, out _, out string state); - if (!isRunning || state != "Running") + if (SelectedInstance.EngineType == EngineType.Bedrock) { - var txtPath = Path.Combine(SelectedInstance.Path, "banned-players.txt"); - await File.AppendAllTextAsync(txtPath, target + Environment.NewLine); + await _banSidecarService.AddBanAsync(SelectedInstance.Path, target, "Banned by administrator"); + } + else + { + bool isRunning = _processRunner.TryGetRunningInfo(SelectedInstance.Slug, out _, out string state); + if (!isRunning || state != "Running") + { + await _fileLock.WaitAsync(); + try + { + var txtPath = Path.Combine(SelectedInstance.Path, "banned-players.txt"); + await File.AppendAllTextAsync(txtPath, target + Environment.NewLine); + } + finally + { + _fileLock.Release(); + } + } } } @@ -250,14 +294,31 @@ private async Task UnbanPlayerAsync(string? username) if (SelectedInstance != null) { - bool isRunning = _processRunner.TryGetRunningInfo(SelectedInstance.Slug, out _, out string state); - if (!isRunning || state != "Running") + if (SelectedInstance.EngineType == EngineType.Bedrock) + { + await _banSidecarService.RemoveBanAsync(SelectedInstance.Path, username); + } + else { - var txtPath = Path.Combine(SelectedInstance.Path, "banned-players.txt"); - if (File.Exists(txtPath)) + bool isRunning = _processRunner.TryGetRunningInfo(SelectedInstance.Slug, out _, out string state); + if (!isRunning || state != "Running") { - var lines = File.ReadAllLines(txtPath).Where(l => !l.Trim().Equals(username, StringComparison.OrdinalIgnoreCase)); - File.WriteAllLines(txtPath, lines); + await _fileLock.WaitAsync(); + try + { + var txtPath = Path.Combine(SelectedInstance.Path, "banned-players.txt"); + if (File.Exists(txtPath)) + { + var lines = File.ReadAllLines(txtPath) + .Where(l => !l.Trim().Equals(username, StringComparison.OrdinalIgnoreCase)) + .ToList(); + File.WriteAllLines(txtPath, lines); + } + } + finally + { + _fileLock.Release(); + } } } } @@ -307,11 +368,20 @@ private async Task RemoveOpPlayerAsync(string? username) private void GoBack() { - var mainVM = App.Services.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; - if (mainVM != null) + var navService = App.Services?.GetService(typeof(PocketMC.App.Navigation.IAppNavigationService)) as PocketMC.App.Navigation.IAppNavigationService; + if (navService?.CanNavigateBack == true) + { + navService.NavigateBack(); + } + else if (navService != null) + { + navService.NavigateToDashboard(); + } + else { - var dashVM = App.Services.GetService(typeof(DashboardViewModel)) as DashboardViewModel; - if (dashVM != null) + var mainVM = App.Services?.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; + var dashVM = App.Services?.GetService(typeof(DashboardViewModel)) as DashboardViewModel; + if (mainVM != null && dashVM != null) { mainVM.CurrentViewModel = dashVM; } diff --git a/PocketMC.App/ViewModels/Players/PlayerViewModel.cs b/PocketMC.App/ViewModels/Players/PlayerViewModel.cs new file mode 100644 index 0000000..de403e5 --- /dev/null +++ b/PocketMC.App/ViewModels/Players/PlayerViewModel.cs @@ -0,0 +1,115 @@ +using System; +using System.Collections.ObjectModel; +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; + +namespace PocketMC.App.ViewModels.Players; + +public partial class PlayerViewModel : ObservableObject +{ + private readonly Func? _toggleOpAsync; + private readonly Func? _changeGamemodeAsync; + private readonly Func>? _submitReasonAsync; + + [ObservableProperty] + private string _name; + + [ObservableProperty] + private bool _isOp; + + [ObservableProperty] + private bool _isBanned; + + [ObservableProperty] + private bool _isOpLoading; + + [ObservableProperty] + private string _selectedGameMode = "survival"; + + [ObservableProperty] + private bool _isReasonPromptVisible; + + [ObservableProperty] + private string _pendingReason = string.Empty; + + [ObservableProperty] + private string _pendingReasonAction = string.Empty; + + public ObservableCollection GameModes { get; } = new(new[] { "survival", "creative", "adventure", "spectator" }); + + public PlayerViewModel( + string name, + Func? toggleOpAsync = null, + Func? changeGamemodeAsync = null, + Func>? submitReasonAsync = null) + { + _name = name; + _toggleOpAsync = toggleOpAsync; + _changeGamemodeAsync = changeGamemodeAsync; + _submitReasonAsync = submitReasonAsync; + } + + [RelayCommand] + public async Task ToggleOpAsync() + { + if (_toggleOpAsync != null) + { + IsOpLoading = true; + try + { + await _toggleOpAsync(this); + } + finally + { + IsOpLoading = false; + } + } + } + + [RelayCommand] + public async Task ChangeGamemodeAsync(string newMode) + { + if (_changeGamemodeAsync != null && !string.IsNullOrWhiteSpace(newMode)) + { + SelectedGameMode = newMode; + await _changeGamemodeAsync(this, newMode); + } + } + + [RelayCommand] + public void PromptKick() + { + PendingReasonAction = "Kick"; + PendingReason = string.Empty; + IsReasonPromptVisible = true; + } + + [RelayCommand] + public void PromptBan() + { + PendingReasonAction = "Ban"; + PendingReason = string.Empty; + IsReasonPromptVisible = true; + } + + [RelayCommand] + public async Task ConfirmReasonAsync() + { + if (_submitReasonAsync != null) + { + bool success = await _submitReasonAsync(this, PendingReasonAction, PendingReason); + if (success) + { + IsReasonPromptVisible = false; + } + } + } + + [RelayCommand] + public void CancelReason() + { + IsReasonPromptVisible = false; + PendingReason = string.Empty; + } +} diff --git a/PocketMC.App/ViewModels/PortsMapViewModel.cs b/PocketMC.App/ViewModels/PortsMapViewModel.cs new file mode 100644 index 0000000..b1c55ba --- /dev/null +++ b/PocketMC.App/ViewModels/PortsMapViewModel.cs @@ -0,0 +1,452 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using PocketMC.Core.Models; +using PocketMC.Core.Services; +using PocketMC.RemoteControl.Services; +using PocketMC.RemoteControl.Tunnels; + +namespace PocketMC.App.ViewModels +{ + public partial class PortsMapViewModel : ObservableObject + { + private readonly IInstanceService _instanceService; + private readonly IProcessRunner _processRunner; + private readonly PlayitApiClient _playitApiClient; + private readonly ISettingsService _settingsService; + + [ObservableProperty] + private bool _isLoading; + + [ObservableProperty] + private string _statusMessage = string.Empty; + + [ObservableProperty] + private ObservableCollection _serverGroups = new(); + + public PortsMapViewModel( + IInstanceService instanceService, + IProcessRunner processRunner, + PlayitApiClient playitApiClient, + ISettingsService settingsService) + { + _instanceService = instanceService; + _processRunner = processRunner; + _playitApiClient = playitApiClient; + _settingsService = settingsService; + } + + [RelayCommand] + public async Task RefreshMapAsync() + { + IsLoading = true; + StatusMessage = "Discovering server ports and active network routes..."; + + try + { + var instances = await _instanceService.ListInstancesAsync(); + var tunnelsResult = await _playitApiClient.GetTunnelsAsync(); + var tunnels = tunnelsResult.Success ? tunnelsResult.Tunnels : new List(); + + var groups = new List(); + + foreach (var inst in instances) + { + bool isOnline = _processRunner.TryGetRunningInfo(inst.Slug, out _, out var state) && + string.Equals(state, "running", StringComparison.OrdinalIgnoreCase); + + var group = new ServerGroupViewModel + { + ServerId = inst.Id, + ServerName = inst.Name, + ServerInfo = $"{inst.EngineType} {inst.EngineVersion}", + IsOnline = isOnline, + IsExpanded = isOnline || instances.Count == 1, + ActiveColorHex = isOnline ? "#00E676" : "#888888" + }; + + var routes = DiscoverInstanceRoutes(inst, isOnline, tunnels); + foreach (var route in routes) + { + group.Routes.Add(route); + } + + groups.Add(group); + } + + ServerGroups.Clear(); + foreach (var g in groups) + { + ServerGroups.Add(g); + } + + StatusMessage = ServerGroups.Count == 0 ? "No server instances found." : string.Empty; + } + catch (Exception ex) + { + StatusMessage = $"Failed to discover network topology: {ex.Message}"; + } + finally + { + IsLoading = false; + } + } + + private List DiscoverInstanceRoutes(ServerInstance inst, bool isOnline, List tunnels) + { + var routes = new List(); + if (string.IsNullOrEmpty(inst.Path) || !Directory.Exists(inst.Path)) + { + return routes; + } + + var serverPropsPath = Path.Combine(inst.Path, "server.properties"); + var properties = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (File.Exists(serverPropsPath)) + { + properties = ServerPropertiesHelper.ReadProperties(serverPropsPath); + } + + bool isBedrockFamily = inst.EngineType == EngineType.Bedrock || inst.EngineType == EngineType.PocketMine; + + // 1. Primary Game Port + int gamePort = isBedrockFamily ? 19132 : 25565; + if (properties.TryGetValue("server-port", out var spStr) && int.TryParse(spStr, out int sp)) + { + gamePort = sp; + } + string gameProtocol = isBedrockFamily ? "UDP" : "TCP"; + routes.Add(CreateRoute( + inst, + gamePort, + gameProtocol, + "GamePort", + isBedrockFamily ? "Minecraft Bedrock Port" : "Minecraft Java Port", + isBedrockFamily ? "Standard Bedrock dedicated server endpoint" : "Standard Java server endpoint", + isOnline, + tunnels)); + + // 2. RCON Port (Java only, if enabled) + if (!isBedrockFamily && properties.TryGetValue("enable-rcon", out var rconEnabled) && string.Equals(rconEnabled, "true", StringComparison.OrdinalIgnoreCase)) + { + int rconPort = 25575; + if (properties.TryGetValue("rcon.port", out var rpStr) && int.TryParse(rpStr, out int rp)) + { + rconPort = rp; + } + routes.Add(CreateRoute( + inst, + rconPort, + "TCP", + "RconPort", + "RCON Remote Management", + "Remote console administrative endpoint", + isOnline, + tunnels)); + } + + // 3. Query Port (if enabled) + if (properties.TryGetValue("enable-query", out var queryEnabled) && string.Equals(queryEnabled, "true", StringComparison.OrdinalIgnoreCase)) + { + int queryPort = gamePort; + if (properties.TryGetValue("query.port", out var qpStr) && int.TryParse(qpStr, out int qp)) + { + queryPort = qp; + } + routes.Add(CreateRoute( + inst, + queryPort, + "UDP", + "QueryPort", + "Query Protocol Port", + "GameSpy4 status and server ping protocol", + isOnline, + tunnels)); + } + + // 4. Geyser Bedrock UDP Port (if installed or Bedrock crossplay configured) + var geyserConfigPath = Path.Combine(inst.Path, "plugins", "Geyser-Spigot", "config.yml"); + if (File.Exists(geyserConfigPath)) + { + int geyserPort = 19132; + try + { + var lines = File.ReadAllLines(geyserConfigPath); + foreach (var line in lines) + { + var trimmed = line.Trim(); + if (trimmed.StartsWith("port:", StringComparison.OrdinalIgnoreCase)) + { + var parts = trimmed.Split(':', 2); + if (parts.Length == 2 && int.TryParse(parts[1].Trim(), out int gp)) + { + geyserPort = gp; + break; + } + } + } + } + catch { } + + routes.Add(CreateRoute( + inst, + geyserPort, + "UDP", + "GeyserPort", + "Geyser Crossplay UDP", + "Bedrock protocol translation endpoint for Java", + isOnline, + tunnels)); + } + + // 5. Simple Voice Chat UDP Port (if installed) + var voiceChatPropsPath = Path.Combine(inst.Path, "plugins", "voicechat", "voicechat-server.properties"); + if (File.Exists(voiceChatPropsPath)) + { + int voicePort = 24454; + try + { + var lines = File.ReadAllLines(voiceChatPropsPath); + foreach (var line in lines) + { + var trimmed = line.Trim(); + if (trimmed.StartsWith("port", StringComparison.OrdinalIgnoreCase) && trimmed.Contains('=')) + { + var parts = trimmed.Split('=', 2); + if (parts.Length == 2 && int.TryParse(parts[1].Trim(), out int vp)) + { + voicePort = vp; + break; + } + } + } + } + catch { } + + routes.Add(CreateRoute( + inst, + voicePort, + "UDP", + "VoiceChatPort", + "Simple Voice Chat UDP", + "Proximity voice chat audio streaming socket", + isOnline, + tunnels)); + } + + return routes; + } + + private PortRouteViewModel CreateRoute( + ServerInstance inst, + int port, + string protocol, + string portType, + string roleName, + string roleDetail, + bool isOnline, + List tunnels) + { + var matchingTunnel = tunnels.FirstOrDefault(t => t.Port == port); + bool hasTunnel = matchingTunnel != null; + + string publicAddress = matchingTunnel?.PublicAddress ?? string.Empty; + string publicAddressLabel = hasTunnel + ? (!string.IsNullOrEmpty(publicAddress) ? publicAddress : "Allocating Address...") + : "No active Playit tunnel"; + + return new PortRouteViewModel + { + ServerId = inst.Id, + ServerName = inst.Name, + Port = port, + Protocol = protocol, + PortType = portType, + ServiceRoleName = roleName, + ServiceRoleDetail = roleDetail, + LocalPortLabel = $"{port} / {protocol}", + PublicAddress = publicAddress, + PublicAddressLabel = publicAddressLabel, + HasTunnel = hasTunnel, + IsOnline = isOnline, + ActiveColorHex = isOnline ? "#00E676" : "#888888" + }; + } + + [RelayCommand] + public void EditPort(PortRouteViewModel? route) + { + if (route == null) return; + if (route.IsOnline) + { + StatusMessage = $"Cannot edit port for '{route.ServerName}' while server is running. Stop the server first."; + return; + } + + foreach (var g in ServerGroups) + { + foreach (var r in g.Routes) + { + if (r != route) r.IsEditingPort = false; + } + } + + route.EditingPortText = route.Port.ToString(); + route.IsEditingPort = true; + } + + [RelayCommand] + public void CancelEditPort(PortRouteViewModel? route) + { + if (route == null) return; + route.IsEditingPort = false; + } + + [RelayCommand] + public async Task SavePortAsync(PortRouteViewModel? route) + { + if (route == null) return; + if (!int.TryParse(route.EditingPortText, out int newPort) || newPort < 1 || newPort > 65535) + { + StatusMessage = "Please enter a valid port between 1 and 65535."; + return; + } + + if (route.IsOnline) + { + StatusMessage = "Cannot change port while server is running."; + return; + } + + var instances = await _instanceService.ListInstancesAsync(); + var targetInstance = instances.FirstOrDefault(i => i.Id == route.ServerId); + if (targetInstance == null || string.IsNullOrEmpty(targetInstance.Path)) + { + StatusMessage = "Instance directory not found."; + return; + } + + if (route.PortType == "GamePort" || route.PortType == "RconPort" || route.PortType == "QueryPort") + { + string propKey = route.PortType switch + { + "GamePort" => "server-port", + "RconPort" => "rcon.port", + "QueryPort" => "query.port", + _ => "server-port" + }; + ServerPropertiesHelper.UpdateProperty(targetInstance.Path, propKey, newPort.ToString()); + } + + route.Port = newPort; + route.LocalPortLabel = $"{newPort} / {route.Protocol}"; + route.IsEditingPort = false; + StatusMessage = $"Updated {route.ServiceRoleName} to port {newPort} successfully."; + } + + [RelayCommand] + public async Task CopyAddressAsync(string? address) + { + if (string.IsNullOrEmpty(address)) return; + if (Avalonia.Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop && desktop.MainWindow != null) + { + var topLevel = Avalonia.Controls.TopLevel.GetTopLevel(desktop.MainWindow); + if (topLevel?.Clipboard != null) + { + await topLevel.Clipboard.SetTextAsync(address); + StatusMessage = $"Copied {address} to clipboard."; + } + } + } + + [RelayCommand] + public void GoBack() + { + var navService = App.Services?.GetService(typeof(PocketMC.App.Navigation.IAppNavigationService)) as PocketMC.App.Navigation.IAppNavigationService; + if (navService?.CanNavigateBack == true) + { + navService.NavigateBack(); + } + else if (navService != null) + { + navService.NavigateToTunnel(); + } + else + { + var mainVM = App.Services?.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; + var tunnelVM = App.Services?.GetService(typeof(TunnelViewModel)) as TunnelViewModel; + if (mainVM != null && tunnelVM != null) + { + mainVM.CurrentViewModel = tunnelVM; + } + } + } + + [RelayCommand] + public void NavigateToConsole(Guid serverId) + { + var navService = App.Services?.GetService(typeof(PocketMC.App.Navigation.IAppNavigationService)) as PocketMC.App.Navigation.IAppNavigationService; + var consoleVM = App.Services?.GetService(typeof(ServerConsoleViewModel)) as ServerConsoleViewModel; + if (consoleVM != null) + { + if (navService != null) + { + navService.NavigateToDetailPage(consoleVM, "Server Console", PocketMC.App.Navigation.DetailRouteKind.ServerConsole, PocketMC.App.Navigation.DetailBackNavigation.PreviousDetail); + } + else + { + var mainVM = App.Services?.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; + if (mainVM != null) mainVM.CurrentViewModel = consoleVM; + } + } + } + } + + public partial class ServerGroupViewModel : ObservableObject + { + public Guid ServerId { get; set; } + public string ServerName { get; set; } = string.Empty; + public string ServerInfo { get; set; } = string.Empty; + public bool IsOnline { get; set; } + + [ObservableProperty] + private bool _isExpanded; + + public string ActiveColorHex { get; set; } = "#888888"; + public ObservableCollection Routes { get; set; } = new(); + } + + public partial class PortRouteViewModel : ObservableObject + { + public Guid ServerId { get; set; } + public string ServerName { get; set; } = string.Empty; + + [ObservableProperty] + private int _port; + + public string PortType { get; set; } = string.Empty; + public string Protocol { get; set; } = "TCP"; + + [ObservableProperty] + private string _localPortLabel = string.Empty; + + public string PublicAddress { get; set; } = string.Empty; + public string PublicAddressLabel { get; set; } = string.Empty; + public bool HasTunnel { get; set; } + public bool IsOnline { get; set; } + public string ActiveColorHex { get; set; } = "#888888"; + public string ServiceRoleName { get; set; } = string.Empty; + public string ServiceRoleDetail { get; set; } = string.Empty; + + [ObservableProperty] + private bool _isEditingPort; + + [ObservableProperty] + private string _editingPortText = string.Empty; + } +} diff --git a/PocketMC.App/ViewModels/RemoteControlUserViewModel.cs b/PocketMC.App/ViewModels/RemoteControlUserViewModel.cs new file mode 100644 index 0000000..e49943c --- /dev/null +++ b/PocketMC.App/ViewModels/RemoteControlUserViewModel.cs @@ -0,0 +1,80 @@ +using System; +using CommunityToolkit.Mvvm.ComponentModel; +using PocketMC.Core.Models; + +namespace PocketMC.App.ViewModels; + +public partial class RemoteControlUserViewModel : ObservableObject +{ + private readonly Action? _onModified; + public RemoteControlUser Model { get; } + + public string SavedUsername { get; set; } = string.Empty; + + public string PasswordHash + { + get => Model.PasswordHash ?? string.Empty; + set => Model.PasswordHash = value; + } + + [ObservableProperty] + private string _username = string.Empty; + + [ObservableProperty] + private string _password = string.Empty; + + [ObservableProperty] + private bool _allowRemoteConsoleCommands; + + [ObservableProperty] + private bool _allowRemotePlayerActions; + + [ObservableProperty] + private bool _allowRemoteServerSettings; + + [ObservableProperty] + private bool _allowRemoteServerAddons; + + [ObservableProperty] + private bool _allowRemoteFileManager; + + [ObservableProperty] + private bool _allowRemoteServerBackups; + + [ObservableProperty] + private bool _allowAllInstances = true; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(IsNotEditing))] + private bool _isEditing; + + public bool IsNotEditing => !IsEditing; + + public RemoteControlUserViewModel(RemoteControlUser model, Action? onModified = null) + { + Model = model ?? throw new ArgumentNullException(nameof(model)); + _onModified = onModified; + _username = model.Username ?? string.Empty; + SavedUsername = _username; + _allowRemoteConsoleCommands = model.AllowRemoteConsoleCommands; + _allowRemotePlayerActions = model.AllowRemotePlayerActions; + _allowRemoteServerSettings = model.AllowRemoteServerSettings; + _allowRemoteServerAddons = model.AllowRemoteServerAddons; + _allowRemoteFileManager = model.AllowRemoteFileManager; + _allowRemoteServerBackups = model.AllowRemoteServerBackups; + _allowAllInstances = model.AllowAllInstances; + } + + public void ApplyToModel() + { + Model.Username = Username; + Model.AllowRemoteConsoleCommands = AllowRemoteConsoleCommands; + Model.AllowRemotePlayerActions = AllowRemotePlayerActions; + Model.AllowRemoteServerSettings = AllowRemoteServerSettings; + Model.AllowRemoteServerAddons = AllowRemoteServerAddons; + Model.AllowRemoteFileManager = AllowRemoteFileManager; + Model.AllowRemoteServerBackups = AllowRemoteServerBackups; + Model.AllowAllInstances = AllowAllInstances; + _onModified?.Invoke(); + } +} diff --git a/PocketMC.App/ViewModels/RemoteControlViewModel.cs b/PocketMC.App/ViewModels/RemoteControlViewModel.cs index 5afe4c5..93e9aa6 100755 --- a/PocketMC.App/ViewModels/RemoteControlViewModel.cs +++ b/PocketMC.App/ViewModels/RemoteControlViewModel.cs @@ -1,24 +1,74 @@ using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; using System.IO; +using System.Linq; +using System.Threading; using System.Threading.Tasks; +using Avalonia; +using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Media.Imaging; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using PocketMC.Core.Models; using PocketMC.Core.Services; +using PocketMC.Infrastructure.Configuration; +using PocketMC.RemoteControl.Models; using PocketMC.RemoteControl.Services; using QRCoder; -using System.Linq; -using Microsoft.Extensions.DependencyInjection; - namespace PocketMC.App.ViewModels; -public partial class RemoteControlViewModel : ObservableObject +public sealed partial class RemoteControlViewModel : ObservableObject, IDisposable { + public sealed record RemoteAccessModeOption(RemoteAccessMode Mode, string Label); + + public static IReadOnlyList RemoteAccessModeOptions { get; } = + [ + new(RemoteAccessMode.CloudflaredQuickTunnel, "Cloudflare Quick Tunnel"), + new(RemoteAccessMode.PlayitHttpsTunnel, "PlayIt Premium HTTPS") + ]; + + public IReadOnlyList AccessModes => RemoteAccessModeOptions; + + public RemoteAccessModeOption? SelectedAccessModeOption + { + get => AccessModes.FirstOrDefault(m => m.Mode == AccessMode); + set + { + if (value != null && value.Mode != AccessMode) + { + AccessMode = value.Mode; + OnPropertyChanged(nameof(SelectedAccessModeOption)); + } + } + } + private readonly ISettingsService _settingsService; + private readonly RemoteControlCoordinator _coordinator; private readonly RemoteAuthenticationService _authService; private readonly LocalNetworkAddressService _networkAddressService; + private readonly IDialogService? _dialogService; + private CancellationTokenSource? _statusCts; + private bool _isRestarting; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(IsGeneralTab))] + [NotifyPropertyChangedFor(nameof(IsUsersTab))] + private int _selectedTab = 0; + + public bool IsGeneralTab + { + get => SelectedTab == 0; + set { if (value) SelectedTab = 0; } + } + + public bool IsUsersTab + { + get => SelectedTab == 1; + set { if (value) SelectedTab = 1; } + } [ObservableProperty] private bool _isEnabled; @@ -26,137 +76,617 @@ public partial class RemoteControlViewModel : ObservableObject [ObservableProperty] private int _port; + [ObservableProperty] + private RemoteAccessMode _accessMode; + [ObservableProperty] private bool _requireAuthentication; [ObservableProperty] - private string _password; + private string? _username; [ObservableProperty] - private bool _allowRemoteConsoleCommands; + private string _password = string.Empty; [ObservableProperty] - private bool _allowRemotePlayerActions; + private bool _isAdminCredentialsExpanded; + + public bool IsPasswordSet => !string.IsNullOrEmpty(_settingsService.Settings.RemoteControl.PasswordHash); + public bool IsPasswordNotSet => string.IsNullOrEmpty(_settingsService.Settings.RemoteControl.PasswordHash); + public bool IsUsernameNotSet => string.IsNullOrEmpty(_settingsService.Settings.RemoteControl.Username); + public bool IsOwnerSetupVisible => RequireAuthentication && IsPasswordNotSet; [ObservableProperty] - private Bitmap? _pairingQrCode; + [NotifyPropertyChangedFor(nameof(IsDiscordNotLinked))] + private bool _isDiscordLinked; + + public bool IsDiscordNotLinked => !IsDiscordLinked; [ObservableProperty] - private string _pairingUrl = ""; + private bool _enableDiscordNotifications; [ObservableProperty] - private bool _isDownloadingUpdate; - + [NotifyPropertyChangedFor(nameof(HasStatusText))] + private string _statusText = string.Empty; + + public bool HasStatusText => !string.IsNullOrWhiteSpace(StatusText); + [ObservableProperty] - private double _updateDownloadProgress; + private bool _isStatusError; [ObservableProperty] - private bool _isUpdateReady; + [NotifyPropertyChangedFor(nameof(HasLocalUrl))] + private string? _localUrl; - private readonly PocketMC.RemoteControl.Hosting.RemoteDashboardHost _dashboardHost; + public bool HasLocalUrl => !string.IsNullOrEmpty(LocalUrl); + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(HasPublicUrl))] + [NotifyPropertyChangedFor(nameof(IsPublicUrlCardVisible))] + private string? _publicUrl; + + public bool HasPublicUrl => !string.IsNullOrEmpty(PublicUrl); + + [ObservableProperty] + private string _publicUrlProviderName = "Cloudflare"; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(IsPublicUrlCardVisible))] + private bool _isLoadingPublicUrl; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(HasPublicUrlError))] + [NotifyPropertyChangedFor(nameof(IsPublicUrlCardVisible))] + private string? _publicUrlErrorText; + + public bool HasPublicUrlError => !string.IsNullOrEmpty(PublicUrlErrorText); + + public bool IsPublicUrlCardVisible => HasPublicUrl || IsLoadingPublicUrl || HasPublicUrlError; + + [ObservableProperty] + private Bitmap? _localQrImage; + + [ObservableProperty] + private Bitmap? _publicQrImage; + + [ObservableProperty] + private bool _isLocalQrVisible; + + [ObservableProperty] + private bool _isPublicQrVisible; + + public ObservableCollection Users { get; } = new(); + + [ObservableProperty] + private RemoteControlUserViewModel? _selectedUser; public RemoteControlViewModel( ISettingsService settingsService, + RemoteControlCoordinator coordinator, RemoteAuthenticationService authService, LocalNetworkAddressService networkAddressService, - PocketMC.RemoteControl.Hosting.RemoteDashboardHost dashboardHost) + IDialogService? dialogService = null) { _settingsService = settingsService; + _coordinator = coordinator; _authService = authService; _networkAddressService = networkAddressService; - _dashboardHost = dashboardHost; - Password = ""; + _dialogService = dialogService; + + var remote = _settingsService.Settings.RemoteControl; + _isEnabled = remote.Enabled; + _port = remote.Port <= 0 ? 25580 : remote.Port; + _requireAuthentication = remote.RequireAuthentication; + _username = remote.Username; + _accessMode = remote.AccessMode == RemoteAccessMode.LanOnly + ? RemoteAccessMode.CloudflaredQuickTunnel + : remote.AccessMode; - LoadSettings(); - GenerateQrCode(); + _isDiscordLinked = !string.IsNullOrEmpty(_settingsService.Settings.DiscordUserId); + _enableDiscordNotifications = _settingsService.Settings.EnableDiscordNotifications; + + if (remote.Users != null) + { + foreach (var user in remote.Users) + { + Users.Add(new RemoteControlUserViewModel(user, () => SaveSettings())); + } + } + + UpdateStatus(); + } + + partial void OnIsEnabledChanged(bool value) + { + if (value && RequireAuthentication && (IsPasswordNotSet || IsUsernameNotSet)) + { + _ = HandleEnableWithCredentialsPromptAsync(); + } + else + { + SaveAndRestart(); + } + } + + private async Task HandleEnableWithCredentialsPromptAsync() + { + if (_dialogService == null) + { + SaveAndRestart(); + return; + } + + bool askUsername = IsUsernameNotSet; + bool askPassword = IsPasswordNotSet; + + while (true) + { + var result = await _dialogService.PromptCredentialsAsync( + "Setup Admin Credentials", + "Remote Control requires authentication to be secure. Please set up the primary admin account, or turn off authentication to continue without it.", + askUsername, + askPassword); + + if (result.Username == null && result.Password == null) + { + RequireAuthentication = false; + SaveAndRestart(); + break; + } + + if ((askUsername && string.IsNullOrWhiteSpace(result.Username)) || + (askPassword && string.IsNullOrWhiteSpace(result.Password))) + { + _dialogService.ShowMessage("Invalid Input", "Username and password cannot be empty. Please enter valid credentials.", DialogType.Warning); + continue; + } + + if (askUsername) Username = result.Username; + if (askPassword) Password = result.Password!; + SaveCredentials(); + SaveAndRestart(); + break; + } + } + + partial void OnPortChanged(int value) + { + SaveAndRestart(); + } + + partial void OnAccessModeChanged(RemoteAccessMode value) + { + OnPropertyChanged(nameof(SelectedAccessModeOption)); + SaveAndRestart(); + } + + partial void OnRequireAuthenticationChanged(bool value) + { + if (value) + { + _settingsService.Settings.RemoteControl.SecurityStamp = Guid.NewGuid().ToString(); + } + SaveSettings(); + OnPropertyChanged(nameof(IsOwnerSetupVisible)); + } + + partial void OnEnableDiscordNotificationsChanged(bool value) + { + _settingsService.Settings.EnableDiscordNotifications = value; + _settingsService.Save(); + } + + [RelayCommand] + private void SaveCredentials() + { + if (string.IsNullOrWhiteSpace(Username) && string.IsNullOrWhiteSpace(Password)) + { + Username = string.Empty; + Password = string.Empty; + _settingsService.Settings.RemoteControl.Username = null; + _settingsService.Settings.RemoteControl.PasswordHash = null; + + _settingsService.Save(); + OnPropertyChanged(nameof(IsPasswordSet)); + OnPropertyChanged(nameof(IsPasswordNotSet)); + OnPropertyChanged(nameof(IsOwnerSetupVisible)); + SetStatus("Admin credentials cleared successfully.", false); + IsAdminCredentialsExpanded = false; + return; + } + + if (string.IsNullOrWhiteSpace(Username)) + { + SetStatus("Username cannot be empty.", true); + Username = _settingsService.Settings.RemoteControl.Username ?? ""; + return; + } + + var trimmedAdminUsername = Username.Trim(); + + if (Users.Any(u => string.Equals(u.Username?.Trim(), trimmedAdminUsername, StringComparison.OrdinalIgnoreCase))) + { + SetStatus("Admin username cannot be the same as an existing sub-user username.", true); + Username = _settingsService.Settings.RemoteControl.Username ?? ""; + return; + } + + if (string.IsNullOrWhiteSpace(Password)) + { + if (!string.IsNullOrEmpty(_settingsService.Settings.RemoteControl.PasswordHash)) + { + Username = trimmedAdminUsername; + _settingsService.Settings.RemoteControl.Username = trimmedAdminUsername; + _settingsService.Settings.RemoteControl.SecurityStamp = Guid.NewGuid().ToString(); + _settingsService.Save(); + OnPropertyChanged(nameof(IsPasswordSet)); + OnPropertyChanged(nameof(IsPasswordNotSet)); + OnPropertyChanged(nameof(IsOwnerSetupVisible)); + SetStatus("Admin username updated successfully.", false); + IsAdminCredentialsExpanded = false; + return; + } + + SetStatus("Password cannot be empty.", true); + return; + } + + Username = trimmedAdminUsername; + _settingsService.Settings.RemoteControl.Username = trimmedAdminUsername; + _settingsService.Settings.RemoteControl.PasswordHash = _authService.HashPassword(Password); + _settingsService.Settings.RemoteControl.SecurityStamp = Guid.NewGuid().ToString(); + + _settingsService.Save(); + OnPropertyChanged(nameof(IsPasswordSet)); + OnPropertyChanged(nameof(IsPasswordNotSet)); + OnPropertyChanged(nameof(IsOwnerSetupVisible)); + SetStatus("Admin credentials saved successfully.", false); + IsAdminCredentialsExpanded = false; + } + + [RelayCommand] + private void AddUser() + { + var user = new RemoteControlUser + { + Username = $"User_{Users.Count + 1}" + }; + var userVm = new RemoteControlUserViewModel(user, () => SaveSettings()) { IsEditing = true }; + Users.Add(userVm); + SelectedUser = userVm; } - private void LoadSettings() + [RelayCommand] + private async Task RemoveUser(RemoteControlUserViewModel? user) { - var settings = _settingsService.Settings.RemoteControl; - IsEnabled = settings.Enabled; - Port = settings.Port == 0 ? 8080 : settings.Port; - RequireAuthentication = settings.RequireAuthentication; - AllowRemoteConsoleCommands = settings.AllowRemoteConsoleCommands; - AllowRemotePlayerActions = settings.AllowRemotePlayerActions; + if (user == null) return; + + if (_dialogService != null) + { + var result = await _dialogService.ShowDialogAsync( + "Remove User", + $"Are you sure you want to remove the user '{user.Username}'? This action cannot be undone.", + DialogType.Warning, + true, + "Remove", + "Cancel"); + + if (result != DialogResult.Ok && result != DialogResult.Yes) + { + return; + } + } + + Users.Remove(user); + SaveSettings(); + SetStatus($"User '{user.Username}' removed successfully.", false); } [RelayCommand] - private async Task SaveSettingsAsync() + private void SaveUser(RemoteControlUserViewModel? user) { - var settings = _settingsService.Settings.RemoteControl; - settings.Enabled = IsEnabled; - settings.Port = Port; - settings.RequireAuthentication = RequireAuthentication; - settings.AllowRemoteConsoleCommands = AllowRemoteConsoleCommands; - settings.AllowRemotePlayerActions = AllowRemotePlayerActions; + if (user == null) return; - if (!string.IsNullOrWhiteSpace(Password)) + if (string.IsNullOrWhiteSpace(user.Username)) { - settings.PasswordHash = _authService.HashPassword(Password); + SetStatus("Username cannot be empty.", true); + if (string.IsNullOrEmpty(user.PasswordHash)) + { + Users.Remove(user); + } + else + { + user.Username = user.SavedUsername; + user.Model.Username = user.SavedUsername; + } + return; + } + + var trimmedUsername = user.Username.Trim(); + + var adminUser = _settingsService.Settings.RemoteControl.Username; + if (!string.IsNullOrEmpty(adminUser) && string.Equals(trimmedUsername, adminUser.Trim(), StringComparison.OrdinalIgnoreCase)) + { + SetStatus("Sub-user username cannot be the same as the admin username.", true); + if (string.IsNullOrEmpty(user.PasswordHash)) + { + Users.Remove(user); + } + else + { + user.Username = user.SavedUsername; + user.Model.Username = user.SavedUsername; + } + return; + } + + if (Users.Any(u => u != user && string.Equals(u.Username?.Trim(), trimmedUsername, StringComparison.OrdinalIgnoreCase))) + { + SetStatus($"User '{trimmedUsername}' already exists.", true); + if (string.IsNullOrEmpty(user.PasswordHash)) + { + Users.Remove(user); + } + else + { + user.Username = user.SavedUsername; + user.Model.Username = user.SavedUsername; + } + return; } + if (string.IsNullOrWhiteSpace(user.Password)) + { + if (!string.IsNullOrEmpty(user.PasswordHash)) + { + user.Username = trimmedUsername; + user.SavedUsername = trimmedUsername; + user.Model.Username = trimmedUsername; + user.IsEditing = false; + if (!SaveSettings()) return; + SetStatus($"User '{user.Username}' updated successfully.", false); + return; + } + + SetStatus("Password is required to save credentials.", true); + return; + } + + var hashed = _authService.HashPassword(user.Password); + user.Username = trimmedUsername; + user.SavedUsername = trimmedUsername; + user.PasswordHash = hashed; + user.IsEditing = false; + + if (!SaveSettings()) return; + SetStatus($"User '{user.Username}' credentials saved successfully.", false); + } + + public bool SaveSettings() + { + var settings = _settingsService.Settings; + if (Port <= 0 || Port > 65535) + { + SetStatus("Remote Control port must be between 1 and 65535.", true); + return false; + } + + settings.RemoteControl.Enabled = IsEnabled; + settings.RemoteControl.Port = Port; + settings.RemoteControl.AccessMode = AccessMode; + settings.RemoteControl.TunnelProviderId = AccessMode switch + { + RemoteAccessMode.CloudflaredQuickTunnel => "cloudflared-quick", + RemoteAccessMode.PlayitHttpsTunnel => "playit-https", + _ => "none" + }; + settings.RemoteControl.RequireAuthentication = RequireAuthentication; + + if (!string.IsNullOrWhiteSpace(Username)) + { + settings.RemoteControl.Username = Username.Trim(); + } + + settings.RemoteControl.Users = Users.Select(u => u.Model).ToList(); _settingsService.Save(); - GenerateQrCode(); + + OnPropertyChanged(nameof(IsPasswordSet)); + OnPropertyChanged(nameof(IsPasswordNotSet)); + OnPropertyChanged(nameof(IsOwnerSetupVisible)); + return true; + } + + public async void SaveAndRestart() + { + if (_isRestarting) return; + if (!SaveSettings()) return; + + _isRestarting = true; + SetStatus(string.Empty, false); try { if (IsEnabled) { - await _dashboardHost.StartServerAsync(Port); + IsLoadingPublicUrl = true; + PublicUrlErrorText = null; + PublicUrl = null; + PublicUrlProviderName = AccessMode switch + { + RemoteAccessMode.CloudflaredQuickTunnel => "Cloudflare", + RemoteAccessMode.PlayitHttpsTunnel => "PlayIt", + _ => "Remote" + }; + await _coordinator.RestartAllAsync(); } else { - await _dashboardHost.StopAsync(CancellationToken.None); + await _coordinator.StopAllAsync(); } } catch (Exception ex) { - Console.WriteLine($"[RemoteControl] Failed to toggle server state: {ex.Message}"); + SetStatus(ex.Message, true); + } + finally + { + _isRestarting = false; + UpdateStatus(); } } + private void UpdateStatus() + { + RemoteDashboardStatus status = _coordinator.GetStatus(); + LocalUrl = status.LocalUrls.FirstOrDefault(); - - [RelayCommand] - private void RestartApp() + PublicUrlProviderName = AccessMode switch + { + RemoteAccessMode.CloudflaredQuickTunnel => "Cloudflare", + RemoteAccessMode.PlayitHttpsTunnel => "PlayIt", + _ => "Remote" + }; + PublicUrl = status.PublicUrl; + PublicUrlErrorText = status.TunnelError; + IsLoadingPublicUrl = false; + + LocalQrImage = GenerateQrCode(LocalUrl); + PublicQrImage = GenerateQrCode(PublicUrl); + + if (string.IsNullOrEmpty(LocalUrl)) + { + IsLocalQrVisible = false; + } + if (string.IsNullOrEmpty(PublicUrl)) + { + IsPublicQrVisible = false; + } + } + + private static Bitmap? GenerateQrCode(string? text) { - // Handle app restart logic + if (string.IsNullOrWhiteSpace(text)) return null; + try + { + using var qrGenerator = new QRCodeGenerator(); + using var qrCodeData = qrGenerator.CreateQrCode(text, QRCodeGenerator.ECCLevel.Q); + using var qrCode = new PngByteQRCode(qrCodeData); + byte[] qrCodeBytes = qrCode.GetGraphic(10); + + using var ms = new MemoryStream(qrCodeBytes); + return new Bitmap(ms); + } + catch + { + return null; + } } - [RelayCommand] - private async Task CopyUrlAsync() + private void SetStatus(string message, bool isError, int autoDismissSeconds = 5) + { + _statusCts?.Cancel(); + _statusCts?.Dispose(); + _statusCts = null; + + StatusText = message; + IsStatusError = isError; + + if (!string.IsNullOrEmpty(message) && autoDismissSeconds > 0) + { + var cts = new CancellationTokenSource(); + _statusCts = cts; + _ = ClearStatusAfterDelayAsync(cts.Token, autoDismissSeconds); + } + } + + private async Task ClearStatusAfterDelayAsync(CancellationToken token, int seconds) { - if (Avalonia.Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop) + try { - if (desktop.MainWindow?.Clipboard != null) + await Task.Delay(TimeSpan.FromSeconds(seconds), token); + if (!token.IsCancellationRequested) { - await desktop.MainWindow.Clipboard.SetTextAsync(PairingUrl); + StatusText = string.Empty; + IsStatusError = false; } } + catch (OperationCanceledException) + { + } } [RelayCommand] - private void NavigateBack() + private void ToggleLocalQr() + { + IsLocalQrVisible = !IsLocalQrVisible; + } + + [RelayCommand] + private void TogglePublicQr() + { + IsPublicQrVisible = !IsPublicQrVisible; + } + + [RelayCommand] + private async Task CopyLocalUrlAsync() + { + if (!string.IsNullOrEmpty(LocalUrl)) + { + await SetClipboardTextAsync(LocalUrl); + } + } + + [RelayCommand] + private async Task CopyPublicUrlAsync() { - var mainVM = App.Services.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; - if (mainVM != null) + if (!string.IsNullOrEmpty(PublicUrl)) { - mainVM.CurrentViewModel = App.Services.GetRequiredService(); + await SetClipboardTextAsync(PublicUrl); } } - private void GenerateQrCode() + private static async Task SetClipboardTextAsync(string text) { - var ip = _networkAddressService.GetLocalIPv4Addresses().FirstOrDefault() ?? "localhost"; - PairingUrl = $"http://{ip}:{Port}/"; + if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop && desktop.MainWindow?.Clipboard != null) + { + await desktop.MainWindow.Clipboard.SetTextAsync(text); + } + } + + [RelayCommand] + private void JoinDiscord() + { + try + { + Process.Start(new ProcessStartInfo + { + FileName = AppUrls.DiscordInvite, + UseShellExecute = true + }); + } + catch + { + } + } - using var qrGenerator = new QRCodeGenerator(); - using var qrCodeData = qrGenerator.CreateQrCode(PairingUrl, QRCodeGenerator.ECCLevel.Q); - using var qrCode = new PngByteQRCode(qrCodeData); - var qrCodeImage = qrCode.GetGraphic(20); + [RelayCommand] + private void NavigateBack() + { + var navService = App.Services?.GetService(typeof(PocketMC.App.Navigation.IAppNavigationService)) as PocketMC.App.Navigation.IAppNavigationService; + if (navService?.CanNavigateBack == true) + { + navService.NavigateBack(); + } + else if (navService != null) + { + navService.NavigateToDashboard(); + } + } - using var stream = new MemoryStream(qrCodeImage); - PairingQrCode = new Bitmap(stream); + public void Dispose() + { + _statusCts?.Cancel(); + _statusCts?.Dispose(); + _statusCts = null; } } diff --git a/PocketMC.App/ViewModels/RootDirectorySetupViewModel.cs b/PocketMC.App/ViewModels/RootDirectorySetupViewModel.cs index 1ccc1d7..e547e4b 100644 --- a/PocketMC.App/ViewModels/RootDirectorySetupViewModel.cs +++ b/PocketMC.App/ViewModels/RootDirectorySetupViewModel.cs @@ -82,12 +82,22 @@ private void Confirm() { Directory.CreateDirectory(SelectedPath); _settingsService.SetDataRoot(SelectedPath); - SetupCompleted?.Invoke(); } catch (Exception ex) { IsError = true; StatusMessage = $"Cannot access directory: {ex.Message}"; + return; + } + + try + { + SetupCompleted?.Invoke(); + } + catch (Exception ex) + { + IsError = true; + StatusMessage = $"Failed to start application: {ex.Message}"; } } } diff --git a/PocketMC.App/ViewModels/ServerBackupsViewModel.cs b/PocketMC.App/ViewModels/ServerBackupsViewModel.cs index 977523e..9cfd50f 100755 --- a/PocketMC.App/ViewModels/ServerBackupsViewModel.cs +++ b/PocketMC.App/ViewModels/ServerBackupsViewModel.cs @@ -199,10 +199,22 @@ private async Task CheckCloudConnectionsAsync() [RelayCommand] private void NavigateBack() { - var mainVM = App.Services.GetService(); - if (mainVM != null) + var navService = App.Services?.GetService(typeof(PocketMC.App.Navigation.IAppNavigationService)) as PocketMC.App.Navigation.IAppNavigationService; + if (navService?.CanNavigateBack == true) { - mainVM.CurrentViewModel = App.Services.GetRequiredService(); + navService.NavigateBack(); + } + else if (navService != null) + { + navService.NavigateToDashboard(); + } + else + { + var mainVM = App.Services?.GetService(); + if (mainVM != null) + { + mainVM.CurrentViewModel = App.Services?.GetRequiredService()!; + } } } @@ -406,7 +418,7 @@ private async Task SaveSettingsAsync() } } - private void UpdateTarget(Settings settings, CloudBackupProviderType provider, bool enabled, int retention) + private void UpdateTarget(PocketMC.Core.Models.Settings settings, CloudBackupProviderType provider, bool enabled, int retention) { var target = settings.CloudBackups.Targets.FirstOrDefault(t => t.Provider == provider); if (target == null) diff --git a/PocketMC.App/ViewModels/ServerConsoleViewModel.cs b/PocketMC.App/ViewModels/ServerConsoleViewModel.cs index af84f5a..2efbc03 100755 --- a/PocketMC.App/ViewModels/ServerConsoleViewModel.cs +++ b/PocketMC.App/ViewModels/ServerConsoleViewModel.cs @@ -10,6 +10,7 @@ using Microsoft.Extensions.DependencyInjection; using PocketMC.Core.Models; using PocketMC.Core.Services; +using PocketMC.App.Services.Console; namespace PocketMC.App.ViewModels { @@ -17,24 +18,13 @@ public class LogLine { public string Text { get; } public string ColorBrush { get; } + public ConsoleLogLevel Level { get; } - public LogLine(string text) + public LogLine(string text, ConsoleLogLevel previousLevel = ConsoleLogLevel.Info) { Text = text; - ColorBrush = Classify(text); - } - - private string Classify(string text) - { - if (text.Contains("[WARN]") || text.Contains("WARN") || text.Contains("Warning")) - return "#FFEB3B"; // Yellow - if (text.Contains("[ERROR]") || text.Contains("ERROR") || text.Contains("Exception") || text.Contains("Failed")) - return "#F44336"; // Red - if (text.Contains("[System]") || text.Contains("System")) - return "#9C27B0"; // Purple - if (text.Contains("joined the game") || text.Contains("left the game") || (text.Contains("<") && text.Contains(">"))) - return "#8BC34A"; // Green (Chat / Player events) - return "#E5E5E5"; // Light Gray / default + Level = LogLineClassifier.Classify(text, previousLevel); + ColorBrush = LogLineClassifier.GetHexColor(Level); } } @@ -62,12 +52,36 @@ public partial class ServerConsoleViewModel : ObservableObject, IDisposable [ObservableProperty] private string _searchQuery = string.Empty; + [ObservableProperty] + private bool _isRegexEnabled; + + [ObservableProperty] + private bool _isFilterChat = true; + + [ObservableProperty] + private bool _isFilterInfo = true; + + [ObservableProperty] + private bool _isFilterWarn = true; + + [ObservableProperty] + private bool _isFilterError = true; + + [ObservableProperty] + private bool _isFilterSystem = true; + [ObservableProperty] private int _logEntryCount; [ObservableProperty] private bool _isCrashed; + [ObservableProperty] + private string _copyButtonText = "Copy Logs"; + + [ObservableProperty] + private bool _isCopied; + public IAsyncRelayCommand SendCommandCommand { get; } public IRelayCommand RefreshInstancesCommand { get; } public IRelayCommand GoBackCommand { get; } @@ -149,14 +163,28 @@ public async Task RefreshInstancesAsync() [RelayCommand] public async Task CopyLogsAsync() { - if (Avalonia.Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop) + var textToCopy = LogLines.Count > 0 + ? string.Join(Environment.NewLine, LogLines.Select(l => l.Text)) + : string.Join(Environment.NewLine, _consoleLogService.GetLogs(SelectedInstance?.Slug ?? string.Empty)); + + if (string.IsNullOrEmpty(textToCopy)) { - var clipboard = desktop.MainWindow?.Clipboard; - if (clipboard != null) + return; + } + + bool success = await PocketMC.App.Services.AppClipboard.SetTextAsync(textToCopy); + if (success) + { + CopyButtonText = "Copied!"; + IsCopied = true; + _ = Task.Delay(2000).ContinueWith(_ => { - var fullText = string.Join(Environment.NewLine, LogLines.Select(l => l.Text)); - await clipboard.SetTextAsync(fullText); - } + Dispatcher.UIThread.Post(() => + { + CopyButtonText = "Copy Logs"; + IsCopied = false; + }); + }); } } @@ -166,10 +194,23 @@ partial void OnSelectedInstanceChanged(ServerInstance? value) UpdateCrashedState(); } - partial void OnSearchQueryChanged(string value) + partial void OnSearchQueryChanged(string value) => ReloadLogs(); + partial void OnIsRegexEnabledChanged(bool value) => ReloadLogs(); + partial void OnIsFilterChatChanged(bool value) => ReloadLogs(); + partial void OnIsFilterInfoChanged(bool value) => ReloadLogs(); + partial void OnIsFilterWarnChanged(bool value) => ReloadLogs(); + partial void OnIsFilterErrorChanged(bool value) => ReloadLogs(); + partial void OnIsFilterSystemChanged(bool value) => ReloadLogs(); + + private bool MatchesFilter(ConsoleLogLevel level) => level switch { - ReloadLogs(); - } + ConsoleLogLevel.Chat => IsFilterChat, + ConsoleLogLevel.Info => IsFilterInfo, + ConsoleLogLevel.Warn => IsFilterWarn, + ConsoleLogLevel.Error => IsFilterError, + ConsoleLogLevel.System => IsFilterSystem, + _ => true + }; private void ReloadLogs() { @@ -180,19 +221,19 @@ private void ReloadLogs() return; } - IReadOnlyList logs; - if (string.IsNullOrWhiteSpace(SearchQuery)) - { - logs = _consoleLogService.GetLogs(SelectedInstance.Slug); - } - else - { - logs = _consoleLogService.SearchLogs(SelectedInstance.Slug, SearchQuery); - } - - foreach (var log in logs) + var allLogs = _consoleLogService.GetLogs(SelectedInstance.Slug); + ConsoleLogLevel prevLevel = ConsoleLogLevel.Info; + foreach (var log in allLogs) { - LogLines.Add(new LogLine(log)); + if (string.IsNullOrWhiteSpace(SearchQuery) || ConsoleLogFilter.MatchesSearch(log, SearchQuery, IsRegexEnabled)) + { + var line = new LogLine(log, prevLevel); + prevLevel = line.Level; + if (MatchesFilter(line.Level)) + { + LogLines.Add(line); + } + } } LogEntryCount = LogLines.Count; } @@ -201,14 +242,28 @@ private void OnLogReceived(string slug, string line) { if (SelectedInstance != null && SelectedInstance.Slug.Equals(slug, StringComparison.OrdinalIgnoreCase)) { - if (string.IsNullOrWhiteSpace(SearchQuery) || line.Contains(SearchQuery, StringComparison.OrdinalIgnoreCase)) + if (string.IsNullOrWhiteSpace(SearchQuery) || ConsoleLogFilter.MatchesSearch(line, SearchQuery, IsRegexEnabled)) { - Dispatcher.UIThread.Post(() => + void AddLine() { - LogLines.Add(new LogLine(line)); - LogEntryCount = LogLines.Count; + var prevLevel = LogLines.Count > 0 ? LogLines[^1].Level : ConsoleLogLevel.Info; + var logLine = new LogLine(line, prevLevel); + if (MatchesFilter(logLine.Level)) + { + LogLines.Add(logLine); + LogEntryCount = LogLines.Count; + } UpdateCrashedState(); - }); + } + + if (Dispatcher.UIThread.CheckAccess()) + { + AddLine(); + } + else + { + Dispatcher.UIThread.Post(AddLine); + } } } } @@ -304,22 +359,43 @@ private void UpdateCrashedState() private void NavigateToAiDiagnostic() { if (SelectedInstance == null) return; - var mainVM = App.Services.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; - if (mainVM != null) + var navService = App.Services?.GetService(typeof(PocketMC.App.Navigation.IAppNavigationService)) as PocketMC.App.Navigation.IAppNavigationService; + var diagnosticVM = App.Services?.GetRequiredService(); + if (diagnosticVM != null) { - var diagnosticVM = App.Services.GetRequiredService(); diagnosticVM.Initialize(SelectedInstance); - mainVM.CurrentViewModel = diagnosticVM; + if (navService != null) + { + navService.NavigateToDetailPage( + diagnosticVM, + $"{SelectedInstance.Name} AI Diagnostics", + PocketMC.App.Navigation.DetailRouteKind.AiDiagnostic, + PocketMC.App.Navigation.DetailBackNavigation.PreviousDetail); + } + else + { + var mainVM = App.Services?.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; + if (mainVM != null) mainVM.CurrentViewModel = diagnosticVM; + } } } private void GoBack() { - var mainVM = App.Services.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; - if (mainVM != null) + var navService = App.Services?.GetService(typeof(PocketMC.App.Navigation.IAppNavigationService)) as PocketMC.App.Navigation.IAppNavigationService; + if (navService?.CanNavigateBack == true) + { + navService.NavigateBack(); + } + else if (navService != null) + { + navService.NavigateToDashboard(); + } + else { - var dashVM = App.Services.GetService(typeof(DashboardViewModel)) as DashboardViewModel; - if (dashVM != null) + var mainVM = App.Services?.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; + var dashVM = App.Services?.GetService(typeof(DashboardViewModel)) as DashboardViewModel; + if (mainVM != null && dashVM != null) { mainVM.CurrentViewModel = dashVM; } diff --git a/PocketMC.App/ViewModels/ServerSettingsViewModel.cs b/PocketMC.App/ViewModels/ServerSettingsViewModel.cs index be1672c..a932d0f 100755 --- a/PocketMC.App/ViewModels/ServerSettingsViewModel.cs +++ b/PocketMC.App/ViewModels/ServerSettingsViewModel.cs @@ -9,6 +9,9 @@ using CommunityToolkit.Mvvm.Input; using PocketMC.Core.Models; using PocketMC.Core.Services; +using PocketMC.Infrastructure.Services; +using PocketMC.App.Services; +using PocketMC.App.ViewModels.Settings; namespace PocketMC.App.ViewModels { @@ -16,6 +19,14 @@ public partial class ServerSettingsViewModel : ObservableObject { private readonly IInstanceService _instanceService; private readonly ISettingsService _settingsService; + private readonly IInstanceUpdateService? _updateService; + private readonly IGeyserDetector _geyserDetector; + private readonly GeyserProvisioningService? _geyserProvisioningService; + private readonly IRebootScheduleService? _rebootScheduleService; + private readonly IDialogService _dialogService; + private readonly IImageProcessingService _imageProcessingService; + private readonly BackupService? _backupService; + private readonly SummaryStorageService _summaryStorageService; private Dictionary _originalProps = new(); private string _originalJvmArgs = string.Empty; @@ -23,55 +34,36 @@ public partial class ServerSettingsViewModel : ObservableObject [ObservableProperty] private ServerInstance? _selectedInstance; - // General settings - [ObservableProperty] private string _motd = string.Empty; - [ObservableProperty] private int _serverPort = 25565; - [ObservableProperty] private int _maxPlayers = 20; - [ObservableProperty] private bool _onlineMode = true; - [ObservableProperty] private bool _whiteList = false; - [ObservableProperty] private string _serverIp = string.Empty; - - // World settings - [ObservableProperty] private string _levelName = "world"; - [ObservableProperty] private string _difficulty = "easy"; - [ObservableProperty] private string _gamemode = "survival"; - [ObservableProperty] private bool _forceGamemode = false; - [ObservableProperty] private bool _hardcore = false; - [ObservableProperty] private string _levelSeed = string.Empty; - [ObservableProperty] private string _levelType = "default"; - [ObservableProperty] private int _spawnProtection = 16; - [ObservableProperty] private bool _generateStructures = true; - [ObservableProperty] private bool _spawnMonsters = true; - [ObservableProperty] private bool _spawnAnimals = true; - [ObservableProperty] private bool _spawnNpcs = true; - - // Performance settings - [ObservableProperty] private int _maxRamGb = 2; - [ObservableProperty] private int _viewDistance = 10; - [ObservableProperty] private int _simulationDistance = 10; - [ObservableProperty] private int _entityBroadcastRange = 100; - [ObservableProperty] private int _networkCompressionThreshold = 256; - [ObservableProperty] private int _maxTickTime = 60000; - - // Advanced settings - [ObservableProperty] private bool _pvp = true; - [ObservableProperty] private bool _allowFlight = false; - [ObservableProperty] private bool _enableCommandBlock = true; - [ObservableProperty] private bool _enableQuery = false; - [ObservableProperty] private int _queryPort = 25565; - [ObservableProperty] private bool _enableRcon = false; - [ObservableProperty] private string _rconPassword = string.Empty; - [ObservableProperty] private int _rconPort = 25575; - [ObservableProperty] private string _resourcePack = string.Empty; - - // Raw Properties - [ObservableProperty] private string _rawPropertiesText = string.Empty; - - [ObservableProperty] private bool _hasUnsavedChanges; - - public List Difficulties { get; } = new() { "peaceful", "easy", "normal", "hard" }; - public List Gamemodes { get; } = new() { "survival", "creative", "adventure", "spectator" }; - public List LevelTypes { get; } = new() { "default", "flat", "large_biomes", "amplified" }; + [ObservableProperty] + private bool _hasGeyser; + + [ObservableProperty] + private int _geyserBedrockPort = 19132; + + [ObservableProperty] + private bool _hasUnsavedChanges; + + [ObservableProperty] + private bool _isRestartRequired; + + // 9 Modular Sub-ViewModels + public SettingsGeneralVM General { get; } + public SettingsWorldVM World { get; } + public SettingsPerformanceVM Performance { get; } + public SettingsBedrockVM Bedrock { get; } + public SettingsBackupsVM Backups { get; } + public SettingsAddonsVM Addons { get; } + public SettingsVersionUpdatesVM VersionUpdates { get; } + public SettingsSummariesVM Summaries { get; } + public SettingsAdvancedVM Advanced { get; } + + public int SubViewModelCount => 9; + + // Backward compatibility convenience accessors + public string Motd { get => General.Motd; set => General.Motd = value; } + public int ServerPort { get => General.ServerPort; set => General.ServerPort = value; } + public string Difficulty { get => World.Difficulty; set => World.Difficulty = value; } + public int MaxRamGb { get => (int)(Performance.MaxRam / 1024.0); set => Performance.MaxRam = value * 1024.0; } public IAsyncRelayCommand SaveCommand { get; } public IRelayCommand CancelCommand { get; } @@ -79,30 +71,84 @@ public partial class ServerSettingsViewModel : ObservableObject public ServerSettingsViewModel( IInstanceService instanceService, - ISettingsService settingsService) + ISettingsService settingsService, + IInstanceUpdateService? updateService = null, + IGeyserDetector? geyserDetector = null, + GeyserProvisioningService? geyserProvisioningService = null, + IRebootScheduleService? rebootScheduleService = null, + IDialogService? dialogService = null, + IImageProcessingService? imageProcessingService = null, + BackupService? backupService = null, + SummaryStorageService? summaryStorageService = null) { _instanceService = instanceService; _settingsService = settingsService; + _updateService = updateService; + _geyserDetector = geyserDetector ?? new GeyserDetector(new AddonManifestService()); + _geyserProvisioningService = geyserProvisioningService; + _rebootScheduleService = rebootScheduleService; + _dialogService = dialogService ?? new AvaloniaDialogService(); + _imageProcessingService = imageProcessingService ?? new ImageProcessingService(); + _backupService = backupService; + _summaryStorageService = summaryStorageService ?? new SummaryStorageService(); + + General = new SettingsGeneralVM(string.Empty, _dialogService, _imageProcessingService, MarkDirty); + World = new SettingsWorldVM(MarkDirty); + Performance = new SettingsPerformanceVM(MarkDirty, _dialogService); + Bedrock = new SettingsBedrockVM(MarkDirty); + Backups = new SettingsBackupsVM(_dialogService, MarkDirty, _backupService); + Addons = new SettingsAddonsVM(_dialogService, MarkDirty); + VersionUpdates = new SettingsVersionUpdatesVM(_updateService); + Summaries = new SettingsSummariesVM(string.Empty, _summaryStorageService, _dialogService); + Advanced = new SettingsAdvancedVM(MarkDirty); SaveCommand = new AsyncRelayCommand(SaveSettingsAsync); CancelCommand = new RelayCommand(CancelEdits); GoBackCommand = new RelayCommand(GoBack); } + private void MarkDirty() + { + HasUnsavedChanges = true; + } + public void Initialize(ServerInstance instance) { SelectedInstance = instance; LoadSettings(); } - private void LoadSettings() + partial void OnSelectedInstanceChanged(ServerInstance? value) + { + if (value != null) + { + General.UpdateServerDir(value.Path); + General.InstanceName = value.Name; + General.InstanceDescription = value.Description ?? string.Empty; + General.ServerPort = value.ServerPort.HasValue && value.ServerPort.Value > 0 ? value.ServerPort.Value : 25565; + + World.UpdateServerDir(value.Path); + Performance.MaxRam = value.MaxRamMb > 0 ? value.MaxRamMb : 2048; + Performance.MinRam = value.MinRamMb > 0 ? value.MinRamMb : 1024; + Performance.AdvancedJvmArgs = value.JvmArgs; + + Backups.SetInstance(value); + Addons.UpdateServerDir(value.Path); + VersionUpdates.SetInstance(value); + Summaries.UpdateServerDir(value.Path); + Advanced.UpdateServerDir(value.Path); + + LoadSettings(); + } + } + + public void LoadSettings() { if (SelectedInstance == null) return; _originalProps.Clear(); _originalJvmArgs = SelectedInstance.JvmArgs ?? string.Empty; - // Load from server.properties string propPath = Path.Combine(SelectedInstance.Path, "server.properties"); if (File.Exists(propPath)) { @@ -116,53 +162,79 @@ private void LoadSettings() var val = trimmed.Substring(idx + 1).Trim(); _originalProps[key] = val; } - RawPropertiesText = File.ReadAllText(propPath); + Advanced.RawPropertiesText = File.ReadAllText(propPath); } else { - RawPropertiesText = "# PocketMC server properties" + Environment.NewLine; + Advanced.RawPropertiesText = "# PocketMC server properties" + Environment.NewLine; } // General - Motd = GetPropValue("motd", "A Minecraft Server"); - ServerPort = GetPropInt("server-port", (SelectedInstance.EngineType == EngineType.PocketMine || SelectedInstance.EngineType == EngineType.Bedrock) ? 19132 : 25565); - MaxPlayers = GetPropInt("max-players", 20); - OnlineMode = GetPropBool("online-mode", true); - WhiteList = GetPropBool("white-list", false) || GetPropBool("enforce-whitelist", false); - ServerIp = GetPropValue("server-ip", ""); + HasGeyser = _geyserDetector.IsGeyserInstalled(SelectedInstance.Path); + General.Motd = GetPropValue("motd", "A Minecraft Server"); + General.ServerPort = GetPropInt("server-port", (SelectedInstance.EngineType == EngineType.PocketMine || SelectedInstance.EngineType == EngineType.Bedrock) ? 19132 : 25565); + General.ServerIp = GetPropValue("server-ip", ""); + General.LoadIcon(); // World - LevelName = GetPropValue("level-name", "world"); - Difficulty = GetPropValue("difficulty", "easy"); - Gamemode = GetPropValue("gamemode", "survival"); - ForceGamemode = GetPropBool("force-gamemode", false); - Hardcore = GetPropBool("hardcore", false); - LevelSeed = GetPropValue("level-seed", ""); - LevelType = GetPropValue("level-type", "default"); - SpawnProtection = GetPropInt("spawn-protection", 16); - GenerateStructures = GetPropBool("generate-structures", true); - SpawnMonsters = GetPropBool("spawn-monsters", true); - SpawnAnimals = GetPropBool("spawn-animals", true); - SpawnNpcs = GetPropBool("spawn-npcs", true); + World.LevelName = GetPropValue("level-name", "world"); + World.Difficulty = GetPropValue("difficulty", "easy"); + World.Gamemode = GetPropValue("gamemode", "survival"); + World.ForceGamemode = GetPropBool("force-gamemode", false); + World.Hardcore = GetPropBool("hardcore", false); + World.Seed = GetPropValue("level-seed", ""); + World.LevelType = GetPropValue("level-type", "default"); + World.SpawnProtection = GetPropInt("spawn-protection", 16); + World.MaxPlayers = GetPropInt("max-players", 20); + World.OnlineMode = GetPropBool("online-mode", true); + World.WhiteList = GetPropBool("white-list", false) || GetPropBool("enforce-whitelist", false); + World.Pvp = GetPropBool("pvp", true); + World.AllowFlight = GetPropBool("allow-flight", false); + World.AllowCommandBlock = GetPropBool("enable-command-block", true); + World.ViewDistance = GetPropInt("view-distance", 10); + World.SimulationDistance = GetPropInt("simulation-distance", 10); + World.GenerateStructures = GetPropBool("generate-structures", true); + World.SpawnMonsters = GetPropBool("spawn-monsters", true); + World.SpawnAnimals = GetPropBool("spawn-animals", true); + World.SpawnNpcs = GetPropBool("spawn-npcs", true); // Performance - MaxRamGb = ParseMaxRam(_originalJvmArgs); - ViewDistance = GetPropInt("view-distance", 10); - SimulationDistance = GetPropInt("simulation-distance", 10); - EntityBroadcastRange = GetPropInt("entity-broadcast-range-percentage", 100); - NetworkCompressionThreshold = GetPropInt("network-compression-threshold", 256); - MaxTickTime = GetPropInt("max-tick-time", 60000); + int parsedRam = ParseMaxRam(_originalJvmArgs); + Performance.MaxRam = parsedRam > 0 ? parsedRam * 1024 : 2048; + + // Bedrock + Bedrock.ServerPortV6 = GetPropValue("server-portv6", "19133"); + Bedrock.AllowCheats = GetPropBool("allow-cheats", false); + Bedrock.TexturepackRequired = GetPropBool("texturepack-required", false); + Bedrock.DefaultPlayerPermissionLevel = GetPropValue("default-player-permission-level", "member"); + Bedrock.TickDistance = GetPropValue("tick-distance", "4"); + Bedrock.ViewDistance = GetPropInt("view-distance", 32); // Advanced - Pvp = GetPropBool("pvp", true); - AllowFlight = GetPropBool("allow-flight", false); - EnableCommandBlock = GetPropBool("enable-command-block", true); - EnableQuery = GetPropBool("enable-query", false); - QueryPort = GetPropInt("query.port", 25565); - EnableRcon = GetPropBool("enable-rcon", false); - RconPassword = GetPropValue("rcon.password", ""); - RconPort = GetPropInt("rcon.port", 25575); - ResourcePack = GetPropValue("resource-pack", ""); + Advanced.Pvp = World.Pvp; + Advanced.AllowFlight = World.AllowFlight; + Advanced.EnableCommandBlock = World.AllowCommandBlock; + Advanced.EnableQuery = GetPropBool("enable-query", false); + Advanced.QueryPort = GetPropInt("query.port", 25565); + Advanced.EnableRcon = GetPropBool("enable-rcon", false); + Advanced.RconPassword = GetPropValue("rcon.password", ""); + Advanced.RconPort = GetPropInt("rcon.port", 25575); + Advanced.ResourcePack = GetPropValue("resource-pack", ""); + + // Scheduled Maintenance + var schedule = _rebootScheduleService?.GetSchedule(SelectedInstance.Slug) ?? SelectedInstance.RebootSchedule; + if (schedule != null) + { + Advanced.EnableScheduledReboot = schedule.Enabled; + Advanced.ScheduledRebootMode = string.IsNullOrEmpty(schedule.Mode) ? "Daily" : schedule.Mode; + Advanced.ScheduledRebootTime = string.IsNullOrEmpty(schedule.Time) ? "04:00" : schedule.Time; + Advanced.ScheduledRebootIntervalHours = schedule.IntervalHours > 0 ? schedule.IntervalHours : 24; + Advanced.ScheduledRebootWarning = schedule.WarningEnabled; + Advanced.ScheduledRebootWarningSeconds = schedule.WarningSeconds > 0 ? schedule.WarningSeconds : 60; + } + + // AI Summaries + Summaries.Load(true); HasUnsavedChanges = false; } @@ -215,7 +287,7 @@ private string SetMaxRam(string jvmArgs, int ramGb) return jvmArgs + " " + newArg; } - private async Task SaveSettingsAsync() + public async Task SaveSettingsAsync() { if (SelectedInstance == null) return; @@ -223,62 +295,90 @@ private async Task SaveSettingsAsync() var updatedProps = new Dictionary(_originalProps); // General - updatedProps["motd"] = Motd; - updatedProps["server-port"] = ServerPort.ToString(); - updatedProps["max-players"] = MaxPlayers.ToString(); - updatedProps["online-mode"] = OnlineMode.ToString().ToLowerInvariant(); - updatedProps["white-list"] = WhiteList.ToString().ToLowerInvariant(); - updatedProps["enforce-whitelist"] = WhiteList.ToString().ToLowerInvariant(); - updatedProps["server-ip"] = ServerIp; + updatedProps["motd"] = General.Motd; + updatedProps["server-port"] = General.ServerPort.ToString(); + updatedProps["server-ip"] = General.ServerIp; // World - updatedProps["level-name"] = LevelName; - updatedProps["difficulty"] = Difficulty; - updatedProps["gamemode"] = Gamemode; - updatedProps["force-gamemode"] = ForceGamemode.ToString().ToLowerInvariant(); - updatedProps["hardcore"] = Hardcore.ToString().ToLowerInvariant(); - updatedProps["level-seed"] = LevelSeed; - updatedProps["level-type"] = LevelType; - updatedProps["spawn-protection"] = SpawnProtection.ToString(); - updatedProps["generate-structures"] = GenerateStructures.ToString().ToLowerInvariant(); - updatedProps["spawn-monsters"] = SpawnMonsters.ToString().ToLowerInvariant(); - updatedProps["spawn-animals"] = SpawnAnimals.ToString().ToLowerInvariant(); - updatedProps["spawn-npcs"] = SpawnNpcs.ToString().ToLowerInvariant(); - - // Performance - updatedProps["view-distance"] = ViewDistance.ToString(); - updatedProps["simulation-distance"] = SimulationDistance.ToString(); - updatedProps["entity-broadcast-range-percentage"] = EntityBroadcastRange.ToString(); - updatedProps["network-compression-threshold"] = NetworkCompressionThreshold.ToString(); - updatedProps["max-tick-time"] = MaxTickTime.ToString(); + updatedProps["level-name"] = World.LevelName; + updatedProps["difficulty"] = World.Difficulty; + updatedProps["gamemode"] = World.Gamemode; + updatedProps["force-gamemode"] = World.ForceGamemode.ToString().ToLowerInvariant(); + updatedProps["hardcore"] = World.Hardcore.ToString().ToLowerInvariant(); + updatedProps["level-seed"] = World.Seed; + updatedProps["level-type"] = World.LevelType; + updatedProps["spawn-protection"] = World.SpawnProtection.ToString(); + updatedProps["max-players"] = World.MaxPlayers.ToString(); + updatedProps["online-mode"] = World.OnlineMode.ToString().ToLowerInvariant(); + updatedProps["white-list"] = World.WhiteList.ToString().ToLowerInvariant(); + updatedProps["enforce-whitelist"] = World.WhiteList.ToString().ToLowerInvariant(); + updatedProps["generate-structures"] = World.GenerateStructures.ToString().ToLowerInvariant(); + updatedProps["spawn-monsters"] = World.SpawnMonsters.ToString().ToLowerInvariant(); + updatedProps["spawn-animals"] = World.SpawnAnimals.ToString().ToLowerInvariant(); + updatedProps["spawn-npcs"] = World.SpawnNpcs.ToString().ToLowerInvariant(); + updatedProps["view-distance"] = World.ViewDistance.ToString(); + updatedProps["simulation-distance"] = World.SimulationDistance.ToString(); + + // Bedrock + updatedProps["server-portv6"] = Bedrock.ServerPortV6; + updatedProps["allow-cheats"] = Bedrock.AllowCheats.ToString().ToLowerInvariant(); + updatedProps["texturepack-required"] = Bedrock.TexturepackRequired.ToString().ToLowerInvariant(); + updatedProps["default-player-permission-level"] = Bedrock.DefaultPlayerPermissionLevel; + updatedProps["tick-distance"] = Bedrock.TickDistance; // Advanced - updatedProps["pvp"] = Pvp.ToString().ToLowerInvariant(); - updatedProps["allow-flight"] = AllowFlight.ToString().ToLowerInvariant(); - updatedProps["enable-command-block"] = EnableCommandBlock.ToString().ToLowerInvariant(); - updatedProps["enable-query"] = EnableQuery.ToString().ToLowerInvariant(); - updatedProps["query.port"] = QueryPort.ToString(); - updatedProps["enable-rcon"] = EnableRcon.ToString().ToLowerInvariant(); - if (!string.IsNullOrEmpty(RconPassword)) updatedProps["rcon.password"] = RconPassword; - updatedProps["rcon.port"] = RconPort.ToString(); - if (!string.IsNullOrWhiteSpace(ResourcePack)) updatedProps["resource-pack"] = ResourcePack; + updatedProps["pvp"] = Advanced.Pvp.ToString().ToLowerInvariant(); + updatedProps["allow-flight"] = Advanced.AllowFlight.ToString().ToLowerInvariant(); + updatedProps["enable-command-block"] = Advanced.EnableCommandBlock.ToString().ToLowerInvariant(); + updatedProps["enable-query"] = Advanced.EnableQuery.ToString().ToLowerInvariant(); + updatedProps["query.port"] = Advanced.QueryPort.ToString(); + updatedProps["enable-rcon"] = Advanced.EnableRcon.ToString().ToLowerInvariant(); + if (!string.IsNullOrEmpty(Advanced.RconPassword)) updatedProps["rcon.password"] = Advanced.RconPassword; + updatedProps["rcon.port"] = Advanced.RconPort.ToString(); + if (!string.IsNullOrWhiteSpace(Advanced.ResourcePack)) updatedProps["resource-pack"] = Advanced.ResourcePack; // Write back to server.properties - var lines = new List(); - lines.Add("#PocketMC server properties"); - lines.Add($"#Saved at {DateTime.UtcNow:o}"); + var lines = new List + { + "#PocketMC server properties", + $"#Saved at {DateTime.UtcNow:o}" + }; foreach (var kvp in updatedProps) { lines.Add($"{kvp.Key}={kvp.Value}"); } await File.WriteAllLinesAsync(propPath, lines); - - // Update raw properties text - RawPropertiesText = string.Join(Environment.NewLine, lines); + Advanced.RawPropertiesText = string.Join(Environment.NewLine, lines); // Save RAM changes to JVM args in metadata - SelectedInstance.JvmArgs = SetMaxRam(_originalJvmArgs, MaxRamGb); + int ramGb = (int)(Performance.MaxRam / 1024.0); + if (ramGb < 1) ramGb = 1; + SelectedInstance.JvmArgs = SetMaxRam(_originalJvmArgs, ramGb); + SelectedInstance.MaxRamMb = (int)Performance.MaxRam; + SelectedInstance.MinRamMb = (int)Performance.MinRam; + SelectedInstance.ServerPort = General.ServerPort; + + // Scheduled Maintenance + var schedule = new RebootScheduleSettings + { + Enabled = Advanced.EnableScheduledReboot, + Mode = Advanced.ScheduledRebootMode, + Time = Advanced.ScheduledRebootTime, + IntervalHours = Advanced.ScheduledRebootIntervalHours, + WarningEnabled = Advanced.ScheduledRebootWarning, + WarningSeconds = Advanced.ScheduledRebootWarningSeconds + }; + + if (_rebootScheduleService != null) + { + try + { + await _rebootScheduleService.SaveScheduleAsync(SelectedInstance.Slug, schedule); + } + catch { } + } + SelectedInstance.RebootSchedule = schedule; // Write local instance.json metadata file var metaPath = Path.Combine(SelectedInstance.Path, "instance.json"); @@ -289,6 +389,14 @@ private async Task SaveSettingsAsync() _originalProps = updatedProps; _originalJvmArgs = SelectedInstance.JvmArgs; + if (HasGeyser && _geyserProvisioningService != null) + { + if (int.TryParse(General.GeyserBedrockPort, out int gPort)) + { + _geyserProvisioningService.PatchGeyserConfigPort(SelectedInstance.Path, gPort); + } + } + HasUnsavedChanges = false; } @@ -299,26 +407,24 @@ private void CancelEdits() private void GoBack() { - var mainVM = App.Services.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; - if (mainVM != null) + var navService = App.Services?.GetService(typeof(PocketMC.App.Navigation.IAppNavigationService)) as PocketMC.App.Navigation.IAppNavigationService; + if (navService?.CanNavigateBack == true) { - var dashVM = App.Services.GetService(typeof(DashboardViewModel)) as DashboardViewModel; - if (dashVM != null) + navService.NavigateBack(); + } + else if (navService != null) + { + navService.NavigateToDashboard(); + } + else + { + var mainVM = App.Services?.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; + var dashVM = App.Services?.GetService(typeof(DashboardViewModel)) as DashboardViewModel; + if (mainVM != null && dashVM != null) { mainVM.CurrentViewModel = dashVM; } } } - - protected override void OnPropertyChanged(System.ComponentModel.PropertyChangedEventArgs e) - { - base.OnPropertyChanged(e); - - if (e.PropertyName != nameof(HasUnsavedChanges) && - e.PropertyName != nameof(SelectedInstance)) - { - HasUnsavedChanges = true; - } - } } } diff --git a/PocketMC.App/ViewModels/Settings/SettingsAddonsVM.cs b/PocketMC.App/ViewModels/Settings/SettingsAddonsVM.cs new file mode 100644 index 0000000..57cef40 --- /dev/null +++ b/PocketMC.App/ViewModels/Settings/SettingsAddonsVM.cs @@ -0,0 +1,212 @@ +using System; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using PocketMC.Core.Models; +using PocketMC.Core.Services; + +namespace PocketMC.App.ViewModels.Settings +{ + public partial class AddonItemViewModel : ObservableObject + { + public string FileName { get; set; } = string.Empty; + public string FilePath { get; set; } = string.Empty; + public string DisplayName { get; set; } = string.Empty; + public string Version { get; set; } = string.Empty; + public bool IsPlugin { get; set; } + + [ObservableProperty] + private bool _isEnabled = true; + } + + public partial class SettingsAddonsVM : ObservableObject + { + private string _serverDir = string.Empty; + private readonly IDialogService _dialogService; + private readonly Action _markDirty; + + [ObservableProperty] private bool _autoUpdateAddons = true; + [ObservableProperty] private string _searchText = string.Empty; + [ObservableProperty] private AddonItemViewModel? _selectedAddon; + + public ObservableCollection Plugins { get; } = new(); + public ObservableCollection Mods { get; } = new(); + + public IRelayCommand RefreshCommand { get; } + public IRelayCommand OpenFolderCommand { get; } + public IAsyncRelayCommand ToggleAddonCommand { get; } + public IAsyncRelayCommand DeleteAddonCommand { get; } + + public SettingsAddonsVM(IDialogService dialogService, Action markDirty) + { + _dialogService = dialogService; + _markDirty = markDirty; + + RefreshCommand = new RelayCommand(LoadAddons); + OpenFolderCommand = new RelayCommand(OpenFolder); + ToggleAddonCommand = new AsyncRelayCommand(ToggleAddonAsync); + DeleteAddonCommand = new AsyncRelayCommand(DeleteAddonAsync); + } + + public void UpdateServerDir(string newDir) + { + _serverDir = newDir; + LoadAddons(); + } + + public void LoadAddons() + { + Plugins.Clear(); + Mods.Clear(); + + if (string.IsNullOrEmpty(_serverDir) || !Directory.Exists(_serverDir)) return; + + // Load Plugins + string pluginsDir = Path.Combine(_serverDir, "plugins"); + if (Directory.Exists(pluginsDir)) + { + var files = Directory.GetFiles(pluginsDir, "*.*") + .Where(f => f.EndsWith(".jar", StringComparison.OrdinalIgnoreCase) || + f.EndsWith(".jar.disabled", StringComparison.OrdinalIgnoreCase)); + + foreach (var f in files) + { + var fi = new FileInfo(f); + bool enabled = !f.EndsWith(".disabled", StringComparison.OrdinalIgnoreCase); + string name = fi.Name.Replace(".jar.disabled", "").Replace(".jar", ""); + + if (string.IsNullOrEmpty(SearchText) || name.Contains(SearchText, StringComparison.OrdinalIgnoreCase)) + { + Plugins.Add(new AddonItemViewModel + { + FileName = fi.Name, + FilePath = fi.FullName, + DisplayName = name, + IsEnabled = enabled, + IsPlugin = true + }); + } + } + } + + // Load Mods + string modsDir = Path.Combine(_serverDir, "mods"); + if (Directory.Exists(modsDir)) + { + var files = Directory.GetFiles(modsDir, "*.*") + .Where(f => f.EndsWith(".jar", StringComparison.OrdinalIgnoreCase) || + f.EndsWith(".jar.disabled", StringComparison.OrdinalIgnoreCase)); + + foreach (var f in files) + { + var fi = new FileInfo(f); + bool enabled = !f.EndsWith(".disabled", StringComparison.OrdinalIgnoreCase); + string name = fi.Name.Replace(".jar.disabled", "").Replace(".jar", ""); + + if (string.IsNullOrEmpty(SearchText) || name.Contains(SearchText, StringComparison.OrdinalIgnoreCase)) + { + Mods.Add(new AddonItemViewModel + { + FileName = fi.Name, + FilePath = fi.FullName, + DisplayName = name, + IsEnabled = enabled, + IsPlugin = false + }); + } + } + } + } + + private async Task ToggleAddonAsync(AddonItemViewModel? item) + { + if (item == null || !File.Exists(item.FilePath)) return; + + try + { + string newPath; + if (item.IsEnabled) + { + // Disable it -> append .disabled + newPath = item.FilePath + ".disabled"; + } + else + { + // Enable it -> strip .disabled + newPath = item.FilePath.EndsWith(".disabled", StringComparison.OrdinalIgnoreCase) + ? item.FilePath.Substring(0, item.FilePath.Length - ".disabled".Length) + : item.FilePath; + } + + File.Move(item.FilePath, newPath, true); + item.FilePath = newPath; + item.FileName = Path.GetFileName(newPath); + item.IsEnabled = !item.IsEnabled; + _markDirty(); + } + catch (Exception ex) + { + _dialogService.ShowMessage("Failed to toggle addon", ex.Message, DialogType.Error); + } + } + + private async Task DeleteAddonAsync(AddonItemViewModel? item) + { + if (item == null) return; + + var confirm = await _dialogService.ShowDialogAsync( + "Delete Addon", + $"Are you sure you want to delete '{item.DisplayName}'?", + DialogType.Question, + showCancel: true); + + if (confirm != DialogResult.Ok && confirm != DialogResult.Yes) return; + + try + { + if (File.Exists(item.FilePath)) + { + File.Delete(item.FilePath); + } + LoadAddons(); + _markDirty(); + } + catch (Exception ex) + { + _dialogService.ShowMessage("Delete Failed", ex.Message, DialogType.Error); + } + } + + private void OpenFolder() + { + if (string.IsNullOrEmpty(_serverDir)) return; + + string targetDir = Path.Combine(_serverDir, "plugins"); + if (!Directory.Exists(targetDir)) + { + targetDir = Path.Combine(_serverDir, "mods"); + } + if (!Directory.Exists(targetDir)) + { + targetDir = _serverDir; + } + + try + { + Process.Start(new ProcessStartInfo + { + FileName = targetDir, + UseShellExecute = true + }); + } + catch { } + } + + partial void OnAutoUpdateAddonsChanged(bool value) => _markDirty(); + partial void OnSearchTextChanged(string value) => LoadAddons(); + } +} diff --git a/PocketMC.App/ViewModels/Settings/SettingsAdvancedVM.cs b/PocketMC.App/ViewModels/Settings/SettingsAdvancedVM.cs new file mode 100644 index 0000000..2f4dccc --- /dev/null +++ b/PocketMC.App/ViewModels/Settings/SettingsAdvancedVM.cs @@ -0,0 +1,93 @@ +using System; +using System.Collections.Generic; +using CommunityToolkit.Mvvm.ComponentModel; + +namespace PocketMC.App.ViewModels.Settings +{ + public partial class SettingsAdvancedVM : ObservableObject + { + private string _serverDir = string.Empty; + private readonly Action _markDirty; + + [ObservableProperty] private bool _enableAutoRestart; + [ObservableProperty] private string _maxAutoRestarts = "3"; + [ObservableProperty] private string _autoRestartDelay = "10"; + + // Scheduled Maintenance + [ObservableProperty] private bool _enableScheduledReboot; + [ObservableProperty] private string _scheduledRebootMode = "Daily"; + [ObservableProperty] private string _scheduledRebootTime = "04:00"; + [ObservableProperty] private int _scheduledRebootIntervalHours = 24; + [ObservableProperty] private bool _scheduledRebootWarning = true; + [ObservableProperty] private int _scheduledRebootWarningSeconds = 60; + + public bool IsDailyMode => string.Equals(ScheduledRebootMode, "Daily", StringComparison.OrdinalIgnoreCase); + public bool IsIntervalMode => string.Equals(ScheduledRebootMode, "Interval", StringComparison.OrdinalIgnoreCase); + public bool IsWarningSettingsEnabled => EnableScheduledReboot && ScheduledRebootWarning; + + public List RebootModes { get; } = new() { "Daily", "Interval" }; + + // Server Properties & Ports + [ObservableProperty] private bool _pvp = true; + [ObservableProperty] private bool _allowFlight; + [ObservableProperty] private bool _enableCommandBlock = true; + [ObservableProperty] private bool _enableQuery; + [ObservableProperty] private int _queryPort = 25565; + [ObservableProperty] private bool _enableRcon; + [ObservableProperty] private string _rconPassword = string.Empty; + [ObservableProperty] private int _rconPort = 25575; + [ObservableProperty] private string _resourcePack = string.Empty; + + // Raw Properties + [ObservableProperty] private string _rawPropertiesText = string.Empty; + + public SettingsAdvancedVM(Action markDirty) + { + _markDirty = markDirty; + } + + public void UpdateServerDir(string newDir) + { + _serverDir = newDir; + } + + partial void OnEnableAutoRestartChanged(bool value) => _markDirty(); + partial void OnMaxAutoRestartsChanged(string value) => _markDirty(); + partial void OnAutoRestartDelayChanged(string value) => _markDirty(); + + partial void OnEnableScheduledRebootChanged(bool value) + { + OnPropertyChanged(nameof(IsDailyMode)); + OnPropertyChanged(nameof(IsIntervalMode)); + OnPropertyChanged(nameof(IsWarningSettingsEnabled)); + _markDirty(); + } + + partial void OnScheduledRebootModeChanged(string value) + { + OnPropertyChanged(nameof(IsDailyMode)); + OnPropertyChanged(nameof(IsIntervalMode)); + _markDirty(); + } + + partial void OnScheduledRebootTimeChanged(string value) => _markDirty(); + partial void OnScheduledRebootIntervalHoursChanged(int value) => _markDirty(); + partial void OnScheduledRebootWarningChanged(bool value) + { + OnPropertyChanged(nameof(IsWarningSettingsEnabled)); + _markDirty(); + } + partial void OnScheduledRebootWarningSecondsChanged(int value) => _markDirty(); + + partial void OnPvpChanged(bool value) => _markDirty(); + partial void OnAllowFlightChanged(bool value) => _markDirty(); + partial void OnEnableCommandBlockChanged(bool value) => _markDirty(); + partial void OnEnableQueryChanged(bool value) => _markDirty(); + partial void OnQueryPortChanged(int value) => _markDirty(); + partial void OnEnableRconChanged(bool value) => _markDirty(); + partial void OnRconPasswordChanged(string value) => _markDirty(); + partial void OnRconPortChanged(int value) => _markDirty(); + partial void OnResourcePackChanged(string value) => _markDirty(); + partial void OnRawPropertiesTextChanged(string value) => _markDirty(); + } +} diff --git a/PocketMC.App/ViewModels/Settings/SettingsBackupsVM.cs b/PocketMC.App/ViewModels/Settings/SettingsBackupsVM.cs new file mode 100644 index 0000000..4c2ef08 --- /dev/null +++ b/PocketMC.App/ViewModels/Settings/SettingsBackupsVM.cs @@ -0,0 +1,230 @@ +using System; +using System.Collections.ObjectModel; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using PocketMC.Core.Models; +using PocketMC.Core.Services; +using PocketMC.Infrastructure.Services; + +namespace PocketMC.App.ViewModels.Settings +{ + public class BackupItemViewModel : ObservableObject + { + public string FileName { get; set; } = string.Empty; + public string FilePath { get; set; } = string.Empty; + public DateTime CreatedAtUtc { get; set; } + public long SizeBytes { get; set; } + public string FormattedSize => SizeBytes > 1024 * 1024 + ? $"{(SizeBytes / (1024.0 * 1024.0)):F1} MB" + : $"{(SizeBytes / 1024.0):F1} KB"; + public string FormattedDate => CreatedAtUtc.ToLocalTime().ToString("g"); + public string Trigger { get; set; } = "Manual"; + public string? Label { get; set; } + } + + public partial class SettingsBackupsVM : ObservableObject + { + private ServerInstance? _instance; + private string _serverDir = string.Empty; + private readonly BackupService? _backupService; + private readonly IDialogService _dialogService; + private readonly Func? _isRunningCheck; + private readonly Action _markDirty; + + [ObservableProperty] private int _backupIntervalHours = 24; + [ObservableProperty] private int _maxBackupsToKeep = 5; + [ObservableProperty] private bool _automaticBackupPruningEnabled = true; + [ObservableProperty] private string? _customBackupDirectory; + [ObservableProperty] private bool _isBackingUp; + [ObservableProperty] private double _backupProgressValue; + [ObservableProperty] private string _backupStatusText = string.Empty; + [ObservableProperty] private BackupItemViewModel? _selectedBackup; + + public ObservableCollection BackupList { get; } = new(); + + public IAsyncRelayCommand CreateBackupCommand { get; } + public IAsyncRelayCommand RestoreBackupCommand { get; } + public IAsyncRelayCommand DeleteBackupCommand { get; } + public IAsyncRelayCommand BrowseBackupDirCommand { get; } + + public SettingsBackupsVM( + IDialogService dialogService, + Action markDirty, + BackupService? backupService = null, + Func? isRunningCheck = null) + { + _dialogService = dialogService; + _markDirty = markDirty; + _backupService = backupService; + _isRunningCheck = isRunningCheck; + + CreateBackupCommand = new AsyncRelayCommand(CreateBackupAsync); + RestoreBackupCommand = new AsyncRelayCommand(RestoreBackupAsync); + DeleteBackupCommand = new AsyncRelayCommand(DeleteBackupAsync); + BrowseBackupDirCommand = new AsyncRelayCommand(BrowseBackupDirAsync); + } + + public void SetInstance(ServerInstance instance) + { + _instance = instance; + UpdateServerDir(instance.Path); + } + + public void UpdateServerDir(string newDir) + { + _serverDir = newDir; + LoadBackups(); + } + + public void LoadBackups() + { + BackupList.Clear(); + if (string.IsNullOrEmpty(_serverDir)) return; + + string backupDir = !string.IsNullOrEmpty(CustomBackupDirectory) && Directory.Exists(CustomBackupDirectory) + ? CustomBackupDirectory + : Path.Combine(_serverDir, "backups"); + + if (!Directory.Exists(backupDir)) return; + + var manifest = BackupManifest.Load(_serverDir); + var files = Directory.GetFiles(backupDir, "*.zip") + .Select(f => new FileInfo(f)) + .OrderByDescending(f => f.CreationTimeUtc); + + foreach (var f in files) + { + var entry = manifest.Entries.FirstOrDefault(e => e.FileName.Equals(f.Name, StringComparison.OrdinalIgnoreCase)); + BackupList.Add(new BackupItemViewModel + { + FileName = f.Name, + FilePath = f.FullName, + CreatedAtUtc = entry?.CreatedAtUtc ?? f.CreationTimeUtc, + SizeBytes = f.Length, + Trigger = entry?.Trigger.ToString() ?? "Manual", + Label = entry?.Label + }); + } + } + + private async Task CreateBackupAsync() + { + if (_instance == null || _backupService == null || IsBackingUp) return; + + IsBackingUp = true; + BackupStatusText = "Creating backup..."; + BackupProgressValue = 0; + + try + { + var progress = new Progress(val => BackupProgressValue = val); + await _backupService.CreateBackupAsync( + _instance, + BackupTrigger.Manual, + onProgress: msg => BackupStatusText = msg, + progress: progress); + + BackupStatusText = "Backup completed successfully."; + LoadBackups(); + } + catch (Exception ex) + { + _dialogService.ShowMessage("Backup Failed", ex.Message, DialogType.Error); + BackupStatusText = "Backup failed."; + } + finally + { + IsBackingUp = false; + } + } + + private async Task RestoreBackupAsync() + { + if (SelectedBackup == null || _instance == null || _backupService == null) return; + + if (_isRunningCheck?.Invoke() == true) + { + _dialogService.ShowMessage("Cannot Restore", "Please stop the server before restoring a backup.", DialogType.Warning); + return; + } + + var confirm = await _dialogService.ShowDialogAsync( + "Confirm Restore", + $"Are you sure you want to restore '{SelectedBackup.FileName}'? Current world files will be replaced.", + DialogType.Warning, + showCancel: true); + + if (confirm != DialogResult.Ok && confirm != DialogResult.Yes) return; + + IsBackingUp = true; + BackupStatusText = "Restoring backup..."; + + try + { + await _backupService.RestoreBackupAsync( + _instance, + SelectedBackup.FilePath, + msg => BackupStatusText = msg); + + _dialogService.ShowMessage("Restore Completed", "Backup restored successfully.", DialogType.Information); + BackupStatusText = "Restore completed."; + } + catch (Exception ex) + { + _dialogService.ShowMessage("Restore Failed", ex.Message, DialogType.Error); + BackupStatusText = "Restore failed."; + } + finally + { + IsBackingUp = false; + } + } + + private async Task DeleteBackupAsync() + { + if (SelectedBackup == null) return; + + var confirm = await _dialogService.ShowDialogAsync( + "Delete Backup", + $"Delete backup '{SelectedBackup.FileName}'?", + DialogType.Question, + showCancel: true); + + if (confirm != DialogResult.Ok && confirm != DialogResult.Yes) return; + + try + { + if (File.Exists(SelectedBackup.FilePath)) + { + File.Delete(SelectedBackup.FilePath); + } + LoadBackups(); + } + catch (Exception ex) + { + _dialogService.ShowMessage("Delete Failed", ex.Message, DialogType.Error); + } + } + + private async Task BrowseBackupDirAsync() + { + var dir = await _dialogService.OpenFolderDialogAsync("Select Custom Backup Directory"); + if (!string.IsNullOrEmpty(dir) && Directory.Exists(dir)) + { + CustomBackupDirectory = dir; + } + } + + partial void OnBackupIntervalHoursChanged(int value) => _markDirty(); + partial void OnMaxBackupsToKeepChanged(int value) => _markDirty(); + partial void OnAutomaticBackupPruningEnabledChanged(bool value) => _markDirty(); + partial void OnCustomBackupDirectoryChanged(string? value) + { + _markDirty(); + LoadBackups(); + } + } +} diff --git a/PocketMC.App/ViewModels/Settings/SettingsBedrockVM.cs b/PocketMC.App/ViewModels/Settings/SettingsBedrockVM.cs new file mode 100644 index 0000000..43a014e --- /dev/null +++ b/PocketMC.App/ViewModels/Settings/SettingsBedrockVM.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using CommunityToolkit.Mvvm.ComponentModel; + +namespace PocketMC.App.ViewModels.Settings +{ + public partial class SettingsBedrockVM : ObservableObject + { + private readonly Action _markDirty; + + [ObservableProperty] + private string _serverPortV6 = "19133"; + + [ObservableProperty] + private bool _allowCheats; + + [ObservableProperty] + private bool _texturepackRequired; + + [ObservableProperty] + private bool _forceGamemode; + + [ObservableProperty] + private string _defaultPlayerPermissionLevel = "member"; + + [ObservableProperty] + private string _tickDistance = "4"; + + [ObservableProperty] + private int _viewDistance = 32; + + public List PermissionLevels { get; } = new() { "visitor", "member", "operator" }; + + public SettingsBedrockVM(Action markDirty) + { + _markDirty = markDirty; + } + + partial void OnServerPortV6Changed(string value) => _markDirty(); + partial void OnAllowCheatsChanged(bool value) => _markDirty(); + partial void OnTexturepackRequiredChanged(bool value) => _markDirty(); + partial void OnForceGamemodeChanged(bool value) => _markDirty(); + partial void OnDefaultPlayerPermissionLevelChanged(string value) => _markDirty(); + partial void OnTickDistanceChanged(string value) => _markDirty(); + partial void OnViewDistanceChanged(int value) => _markDirty(); + } +} diff --git a/PocketMC.App/ViewModels/Settings/SettingsGeneralVM.cs b/PocketMC.App/ViewModels/Settings/SettingsGeneralVM.cs new file mode 100644 index 0000000..e9f7ebc --- /dev/null +++ b/PocketMC.App/ViewModels/Settings/SettingsGeneralVM.cs @@ -0,0 +1,133 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using Avalonia.Media.Imaging; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using PocketMC.Core.Models; +using PocketMC.Core.Services; +using PocketMC.App.Services; + +namespace PocketMC.App.ViewModels.Settings +{ + public partial class SettingsGeneralVM : ObservableObject + { + private string _serverDir = string.Empty; + private readonly IDialogService _dialogService; + private readonly IImageProcessingService _imageProcessingService; + private readonly Action _markDirty; + + [ObservableProperty] + private string _motd = "A Minecraft Server"; + + [ObservableProperty] + private string _instanceName = string.Empty; + + [ObservableProperty] + private string _instanceDescription = string.Empty; + + [ObservableProperty] + private bool _autoStartWithApp; + + [ObservableProperty] + private int _serverPort = 25565; + + [ObservableProperty] + private string _geyserBedrockPort = "19132"; + + [ObservableProperty] + private string _pumpkinBedrockPort = "19132"; + + [ObservableProperty] + private string _serverIp = string.Empty; + + [ObservableProperty] + private Bitmap? _serverIcon; + + public IAsyncRelayCommand BrowseIconCommand { get; } + + public SettingsGeneralVM( + string serverDir, + IDialogService dialogService, + IImageProcessingService imageProcessingService, + Action markDirty) + { + _serverDir = serverDir; + _dialogService = dialogService; + _imageProcessingService = imageProcessingService; + _markDirty = markDirty; + + BrowseIconCommand = new AsyncRelayCommand(BrowseIconAsync); + } + + public void UpdateServerDir(string newDir) + { + _serverDir = newDir; + LoadIcon(); + } + + public void LoadIcon() + { + if (string.IsNullOrEmpty(_serverDir)) + { + ServerIcon = null; + return; + } + + var iconPath = Path.Combine(_serverDir, "server-icon.png"); + if (File.Exists(iconPath)) + { + try + { + using var stream = File.OpenRead(iconPath); + ServerIcon = new Bitmap(stream); + } + catch + { + ServerIcon = null; + } + } + else + { + ServerIcon = null; + } + } + + public async Task BrowseIconAsync() + { + var file = await _dialogService.OpenFileDialogAsync("Select Server Icon", "Image Files (*.png;*.jpg;*.jpeg;*.bmp)|*.png;*.jpg;*.jpeg;*.bmp"); + if (!string.IsNullOrEmpty(file) && File.Exists(file)) + { + try + { + byte[] fileBytes = await File.ReadAllBytesAsync(file); + // Crop and resize to 64x64 standard server icon + byte[] croppedBytes = _imageProcessingService.CropAndResizeImage(fileBytes, 0, 0, 0, 64); + + if (!string.IsNullOrEmpty(_serverDir)) + { + var targetPath = Path.Combine(_serverDir, "server-icon.png"); + await File.WriteAllBytesAsync(targetPath, croppedBytes); + } + + using var ms = new MemoryStream(croppedBytes); + ServerIcon = new Bitmap(ms); + _markDirty(); + } + catch (Exception ex) + { + _dialogService.ShowMessage("Image Error", $"Failed to process image: {ex.Message}", DialogType.Error); + } + } + } + + partial void OnMotdChanged(string value) => _markDirty(); + partial void OnInstanceNameChanged(string value) => _markDirty(); + partial void OnInstanceDescriptionChanged(string value) => _markDirty(); + partial void OnAutoStartWithAppChanged(bool value) => _markDirty(); + partial void OnServerPortChanged(int value) => _markDirty(); + partial void OnGeyserBedrockPortChanged(string value) => _markDirty(); + partial void OnPumpkinBedrockPortChanged(string value) => _markDirty(); + partial void OnServerIpChanged(string value) => _markDirty(); + } +} diff --git a/PocketMC.App/ViewModels/Settings/SettingsPerformanceVM.cs b/PocketMC.App/ViewModels/Settings/SettingsPerformanceVM.cs new file mode 100644 index 0000000..ea8a97a --- /dev/null +++ b/PocketMC.App/ViewModels/Settings/SettingsPerformanceVM.cs @@ -0,0 +1,88 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using PocketMC.Core.Services; + +namespace PocketMC.App.ViewModels.Settings +{ + public partial class SettingsPerformanceVM : ObservableObject + { + private readonly IDialogService? _dialogService; + private readonly Action _markDirty; + private readonly double _totalRamMb; + + [ObservableProperty] + private double _minRam = 1024; + + [ObservableProperty] + private double _maxRam = 4096; + + [ObservableProperty] + private bool _showRamWarning; + + [ObservableProperty] + private string? _javaPath; + + [ObservableProperty] + private string? _advancedJvmArgs; + + public string MinRamDisplay => $"{MinRam:N0} MB"; + public string MaxRamDisplay => $"{MaxRam:N0} MB"; + public double TotalRamMb => _totalRamMb; + + public IAsyncRelayCommand BrowseJavaCommand { get; } + + public SettingsPerformanceVM(Action markDirty, IDialogService? dialogService = null) + { + _markDirty = markDirty; + _dialogService = dialogService; + + double memMb = GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / (1024.0 * 1024.0); + _totalRamMb = memMb > 0 ? memMb : 8192; + + BrowseJavaCommand = new AsyncRelayCommand(BrowseJavaAsync); + } + + public async Task BrowseJavaAsync() + { + if (_dialogService == null) return; + + string filter = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) + ? "java.exe|java.exe|Executables (*.exe)|*.exe" + : "Java Executable (java)|java|All Files (*.*)|*.*"; + + var file = await _dialogService.OpenFileDialogAsync("Select Java Executable", filter); + if (!string.IsNullOrEmpty(file) && File.Exists(file)) + { + JavaPath = file; + } + } + + private void CheckRamWarning() + { + if (_totalRamMb > 0) + { + ShowRamWarning = MaxRam > (_totalRamMb * 0.85); + } + } + + partial void OnMinRamChanged(double value) + { + OnPropertyChanged(nameof(MinRamDisplay)); + _markDirty(); + } + + partial void OnMaxRamChanged(double value) + { + OnPropertyChanged(nameof(MaxRamDisplay)); + CheckRamWarning(); + _markDirty(); + } + + partial void OnJavaPathChanged(string? value) => _markDirty(); + partial void OnAdvancedJvmArgsChanged(string? value) => _markDirty(); + } +} diff --git a/PocketMC.App/ViewModels/Settings/SettingsSummariesVM.cs b/PocketMC.App/ViewModels/Settings/SettingsSummariesVM.cs new file mode 100644 index 0000000..72bd0ce --- /dev/null +++ b/PocketMC.App/ViewModels/Settings/SettingsSummariesVM.cs @@ -0,0 +1,144 @@ +using System; +using System.Collections.ObjectModel; +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using PocketMC.Core.Models; +using PocketMC.Core.Services; +using PocketMC.Infrastructure.Services; + +namespace PocketMC.App.ViewModels.Settings +{ + public class SessionSummaryItem : ObservableObject + { + public string FileName { get; set; } = string.Empty; + public string ServerName { get; set; } = string.Empty; + public DateTime SessionStart { get; set; } + public DateTime SessionEnd { get; set; } + public TimeSpan Duration { get; set; } + public string Content { get; set; } = string.Empty; + public string AiProvider { get; set; } = string.Empty; + public DateTime GeneratedAt { get; set; } + + public string FormattedDate => SessionEnd.ToLocalTime().ToString("g"); + public string FormattedDuration => Duration.TotalHours >= 1 + ? $"{(int)Duration.TotalHours}h {Duration.Minutes}m" + : $"{Duration.Minutes}m"; + } + + public partial class SettingsSummariesVM : ObservableObject + { + private string _serverDir = string.Empty; + private readonly SummaryStorageService _storageService; + private readonly IDialogService? _dialogService; + + public ObservableCollection Summaries { get; } = new(); + + [ObservableProperty] private bool _isFeatureAvailable; + [ObservableProperty] private SessionSummaryItem? _selectedSummary; + [ObservableProperty] private string _summaryContent = string.Empty; + [ObservableProperty] private bool _isViewingSummary; + + public bool HasSummaries => Summaries.Count > 0; + public bool HasSelectedSummary => SelectedSummary != null; + + public IRelayCommand ViewSummaryCommand { get; } + public IAsyncRelayCommand DeleteSummaryCommand { get; } + public IRelayCommand CloseSummaryCommand { get; } + + public SettingsSummariesVM( + string serverDir, + SummaryStorageService? storageService = null, + IDialogService? dialogService = null) + { + _serverDir = serverDir; + _storageService = storageService ?? new SummaryStorageService(); + _dialogService = dialogService; + + ViewSummaryCommand = new RelayCommand(ViewSummary); + DeleteSummaryCommand = new AsyncRelayCommand(DeleteSummaryAsync); + CloseSummaryCommand = new RelayCommand(CloseSummary); + } + + public void UpdateServerDir(string newDir) + { + _serverDir = newDir; + Load(IsFeatureAvailable); + } + + public void Load(bool hasApiKey) + { + IsFeatureAvailable = hasApiKey; + Summaries.Clear(); + + if (!hasApiKey || string.IsNullOrEmpty(_serverDir)) + { + OnPropertyChanged(nameof(HasSummaries)); + return; + } + + var items = _storageService.ListSummaries(_serverDir); + foreach (var s in items) + { + Summaries.Add(new SessionSummaryItem + { + FileName = s.FileName, + ServerName = s.ServerName, + SessionStart = s.SessionStart, + SessionEnd = s.SessionEnd, + Duration = s.Duration, + Content = s.Content, + AiProvider = s.AiProvider, + GeneratedAt = s.GeneratedAt + }); + } + + OnPropertyChanged(nameof(HasSummaries)); + } + + public void ViewSummary(SessionSummaryItem? item) + { + if (item == null) return; + SelectedSummary = item; + SummaryContent = item.Content; + IsViewingSummary = true; + } + + public void CloseSummary() + { + IsViewingSummary = false; + SummaryContent = string.Empty; + } + + public async Task DeleteSummaryAsync(SessionSummaryItem? item) + { + if (item == null) return; + + if (_dialogService != null) + { + var confirm = await _dialogService.ShowDialogAsync( + "Delete Summary", + $"Delete summary from {item.FormattedDate}?", + DialogType.Question, + showCancel: true); + + if (confirm != DialogResult.Ok && confirm != DialogResult.Yes) return; + } + + if (_storageService.Delete(_serverDir, item.FileName)) + { + Summaries.Remove(item); + if (SelectedSummary == item) + { + CloseSummary(); + } + OnPropertyChanged(nameof(HasSummaries)); + } + } + + partial void OnSelectedSummaryChanged(SessionSummaryItem? value) + { + OnPropertyChanged(nameof(HasSelectedSummary)); + } + } +} diff --git a/PocketMC.App/ViewModels/Settings/SettingsVersionUpdatesVM.cs b/PocketMC.App/ViewModels/Settings/SettingsVersionUpdatesVM.cs new file mode 100644 index 0000000..42d6227 --- /dev/null +++ b/PocketMC.App/ViewModels/Settings/SettingsVersionUpdatesVM.cs @@ -0,0 +1,170 @@ +using System; +using System.Collections.ObjectModel; +using System.Linq; +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using PocketMC.Core.Models; +using PocketMC.Core.Services; +using PocketMC.Infrastructure.Services; + +namespace PocketMC.App.ViewModels.Settings +{ + public partial class SettingsVersionUpdatesVM : ObservableObject + { + private ServerInstance? _instance; + private readonly IInstanceUpdateService? _updateService; + private readonly Func? _isRunningCheck; + + public ObservableCollection AvailableTargetVersions { get; } = new(); + + [ObservableProperty] private UpdateTargetVersionInfo? _selectedTargetVersion; + [ObservableProperty] private bool _isLoadingTargetVersions; + [ObservableProperty] private bool _isUpdating; + [ObservableProperty] private double _updateProgress; + [ObservableProperty] private string _updateStatusText = string.Empty; + [ObservableProperty] private string _updateErrorText = string.Empty; + [ObservableProperty] private bool _hasUpdateError; + [ObservableProperty] private bool _isUpdateSuccess; + [ObservableProperty] private string _updateRuntimeChangeText = string.Empty; + + public IAsyncRelayCommand LoadTargetVersionsCommand { get; } + public IAsyncRelayCommand ApplyUpdateCommand { get; } + + public SettingsVersionUpdatesVM( + IInstanceUpdateService? updateService = null, + Func? isRunningCheck = null) + { + _updateService = updateService; + _isRunningCheck = isRunningCheck; + + LoadTargetVersionsCommand = new AsyncRelayCommand(LoadTargetVersionsAsync); + ApplyUpdateCommand = new AsyncRelayCommand(ApplyUpdateAsync); + } + + public void SetInstance(ServerInstance instance) + { + _instance = instance; + _ = LoadTargetVersionsAsync(); + } + + public void UpdateServerDir(string newDir) + { + // Server directory updated + } + + partial void OnSelectedTargetVersionChanged(UpdateTargetVersionInfo? value) + { + if (value != null && _instance != null) + { + if (_instance.EngineType == EngineType.PocketMine) + { + UpdateRuntimeChangeText = "PHP 8.2+ managed runtime"; + } + else if (_instance.EngineType == EngineType.Bedrock) + { + UpdateRuntimeChangeText = "Native Bedrock Dedicated Server binary"; + } + else + { + int currJava = InstanceUpdatePlanner.MapMinecraftVersionToJavaVersion(_instance.EngineVersion); + int targetJava = InstanceUpdatePlanner.MapMinecraftVersionToJavaVersion(value.Id); + UpdateRuntimeChangeText = currJava == targetJava + ? $"Java {targetJava} remains compatible" + : $"Java runtime requirement changes: Java {currJava} -> Java {targetJava}"; + } + } + else + { + UpdateRuntimeChangeText = string.Empty; + } + } + + public async Task LoadTargetVersionsAsync() + { + if (_instance == null || _updateService == null) return; + + IsLoadingTargetVersions = true; + AvailableTargetVersions.Clear(); + SelectedTargetVersion = null; + HasUpdateError = false; + IsUpdateSuccess = false; + + try + { + var versions = await _updateService.GetAvailableTargetVersionsAsync(_instance); + foreach (var v in versions) + { + AvailableTargetVersions.Add(v); + } + + SelectedTargetVersion = AvailableTargetVersions.FirstOrDefault(v => v.IsUpgrade) + ?? AvailableTargetVersions.FirstOrDefault(); + } + catch (Exception ex) + { + HasUpdateError = true; + UpdateErrorText = $"Failed to check for updates: {ex.Message}"; + } + finally + { + IsLoadingTargetVersions = false; + } + } + + public async Task ApplyUpdateAsync() + { + if (_instance == null || SelectedTargetVersion == null || _updateService == null || IsUpdating) return; + + if (_isRunningCheck?.Invoke() == true) + { + HasUpdateError = true; + UpdateErrorText = "Please stop the server before applying an update."; + return; + } + + IsUpdating = true; + HasUpdateError = false; + IsUpdateSuccess = false; + UpdateProgress = 0; + UpdateStatusText = $"Starting update to {SelectedTargetVersion.Id}..."; + + var progress = new Progress(val => UpdateProgress = val); + + try + { + var result = await _updateService.UpdateAsync( + _instance, + SelectedTargetVersion.Id, + progress, + status => UpdateStatusText = status); + + if (result.Success) + { + IsUpdateSuccess = true; + _instance.EngineVersion = SelectedTargetVersion.Id; + UpdateStatusText = $"Successfully upgraded to {result.TargetVersionApplied}!"; + await LoadTargetVersionsAsync(); + } + else + { + HasUpdateError = true; + UpdateErrorText = result.ErrorMessage ?? "Unknown update failure occurred."; + UpdateStatusText = result.RestoredFromRollback + ? "Update failed, but original server files were restored safely via rollback journal." + : "Update failed. Please check logs."; + } + } + catch (Exception ex) + { + HasUpdateError = true; + UpdateErrorText = ex.Message; + UpdateStatusText = "Update failed due to an unexpected error."; + } + finally + { + IsUpdating = false; + } + } + } +} diff --git a/PocketMC.App/ViewModels/Settings/SettingsWorldVM.cs b/PocketMC.App/ViewModels/Settings/SettingsWorldVM.cs new file mode 100644 index 0000000..7ce4d6a --- /dev/null +++ b/PocketMC.App/ViewModels/Settings/SettingsWorldVM.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using CommunityToolkit.Mvvm.ComponentModel; + +namespace PocketMC.App.ViewModels.Settings +{ + public partial class SettingsWorldVM : ObservableObject + { + private string _serverDir = string.Empty; + private readonly Action _markDirty; + + [ObservableProperty] private string _seed = string.Empty; + [ObservableProperty] private string _levelName = "world"; + [ObservableProperty] private string _levelType = "default"; + [ObservableProperty] private string _gamemode = "survival"; + [ObservableProperty] private string _difficulty = "easy"; + [ObservableProperty] private bool _pvp = true; + [ObservableProperty] private bool _whiteList; + [ObservableProperty] private bool _onlineMode = true; + [ObservableProperty] private bool _allowCommandBlock = true; + [ObservableProperty] private bool _allowFlight; + [ObservableProperty] private bool _allowNether = true; + [ObservableProperty] private int _spawnProtection = 16; + [ObservableProperty] private int _maxPlayers = 20; + [ObservableProperty] private int _viewDistance = 10; + [ObservableProperty] private int _simulationDistance = 10; + [ObservableProperty] private bool _generateStructures = true; + [ObservableProperty] private bool _spawnMonsters = true; + [ObservableProperty] private bool _spawnAnimals = true; + [ObservableProperty] private bool _spawnNpcs = true; + [ObservableProperty] private bool _forceGamemode; + [ObservableProperty] private bool _hardcore; + + public List Difficulties { get; } = new() { "peaceful", "easy", "normal", "hard" }; + public List Gamemodes { get; } = new() { "survival", "creative", "adventure", "spectator" }; + public List LevelTypes { get; } = new() { "default", "flat", "large_biomes", "amplified" }; + + public SettingsWorldVM(Action markDirty) + { + _markDirty = markDirty; + } + + public void UpdateServerDir(string newDir) + { + _serverDir = newDir; + } + + partial void OnSeedChanged(string value) => _markDirty(); + partial void OnLevelNameChanged(string value) => _markDirty(); + partial void OnLevelTypeChanged(string value) => _markDirty(); + partial void OnGamemodeChanged(string value) => _markDirty(); + partial void OnDifficultyChanged(string value) => _markDirty(); + partial void OnPvpChanged(bool value) => _markDirty(); + partial void OnWhiteListChanged(bool value) => _markDirty(); + partial void OnOnlineModeChanged(bool value) => _markDirty(); + partial void OnAllowCommandBlockChanged(bool value) => _markDirty(); + partial void OnAllowFlightChanged(bool value) => _markDirty(); + partial void OnAllowNetherChanged(bool value) => _markDirty(); + partial void OnSpawnProtectionChanged(int value) => _markDirty(); + partial void OnMaxPlayersChanged(int value) => _markDirty(); + partial void OnViewDistanceChanged(int value) => _markDirty(); + partial void OnSimulationDistanceChanged(int value) => _markDirty(); + partial void OnGenerateStructuresChanged(bool value) => _markDirty(); + partial void OnSpawnMonstersChanged(bool value) => _markDirty(); + partial void OnSpawnAnimalsChanged(bool value) => _markDirty(); + partial void OnSpawnNpcsChanged(bool value) => _markDirty(); + partial void OnForceGamemodeChanged(bool value) => _markDirty(); + partial void OnHardcoreChanged(bool value) => _markDirty(); + } +} diff --git a/PocketMC.App/ViewModels/TunnelViewModel.cs b/PocketMC.App/ViewModels/TunnelViewModel.cs index 6956ac2..7c77c24 100644 --- a/PocketMC.App/ViewModels/TunnelViewModel.cs +++ b/PocketMC.App/ViewModels/TunnelViewModel.cs @@ -250,6 +250,37 @@ private async Task OpenSetupWizardAsync() } } + [RelayCommand] + private async Task OpenConsoleAsync() + { + if (_tunnelManager.GetProvider("playit-https") is { } provider) + { + var consoleWin = new Views.Tunnel.PlayitConsoleWindow(provider.ProcessManager); + if (Avalonia.Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop && desktop.MainWindow != null) + { + await consoleWin.ShowDialog(desktop.MainWindow); + } + else + { + consoleWin.Show(); + } + } + } + + [RelayCommand] + private async Task OpenCreateTunnelDialogAsync() + { + var dialog = new Views.Tunnel.CreateTunnelDialog(_playitApiClient); + if (Avalonia.Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop && desktop.MainWindow != null) + { + await dialog.ShowDialog(desktop.MainWindow); + if (dialog.TunnelCreated) + { + await RefreshAllAsync(); + } + } + } + [RelayCommand] private async Task UnlinkAccountAsync() { @@ -258,13 +289,47 @@ private async Task UnlinkAccountAsync() await RefreshAllAsync(); } + [RelayCommand] + private void OpenPortsMap() + { + var navService = App.Services?.GetService(typeof(PocketMC.App.Navigation.IAppNavigationService)) as PocketMC.App.Navigation.IAppNavigationService; + var portsMapVM = App.Services?.GetService(typeof(PortsMapViewModel)) as PortsMapViewModel; + if (portsMapVM != null) + { + if (navService != null) + { + navService.NavigateToDetailPage(portsMapVM, "Ports Map", PocketMC.App.Navigation.DetailRouteKind.PortsMap, PocketMC.App.Navigation.DetailBackNavigation.Dashboard); + } + else + { + var mainVM = App.Services?.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; + if (mainVM != null) + { + mainVM.CurrentViewModel = portsMapVM; + } + } + } + } + [RelayCommand] private void GoBack() { - var mainVM = App.Services.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; - if (mainVM != null) + var navService = App.Services?.GetService(typeof(PocketMC.App.Navigation.IAppNavigationService)) as PocketMC.App.Navigation.IAppNavigationService; + if (navService?.CanNavigateBack == true) { - mainVM.CurrentViewModel = App.Services.GetRequiredService(); + navService.NavigateBack(); + } + else if (navService != null) + { + navService.NavigateToDashboard(); + } + else + { + var mainVM = App.Services?.GetService(typeof(MainWindowViewModel)) as MainWindowViewModel; + if (mainVM != null) + { + mainVM.CurrentViewModel = App.Services?.GetRequiredService()!; + } } } } diff --git a/PocketMC.App/Views/AboutPage.axaml b/PocketMC.App/Views/AboutPage.axaml index 363b4db..2edf5e7 100644 --- a/PocketMC.App/Views/AboutPage.axaml +++ b/PocketMC.App/Views/AboutPage.axaml @@ -11,7 +11,7 @@ @@ -30,26 +30,142 @@ CornerRadius="12" Padding="24"> - - + + - - + + - - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - @@ -155,7 +273,7 @@ FontSize="12" Opacity="0.7" Foreground="{DynamicResource TextPrimaryBrush}" TextWrapping="Wrap"/> - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + - - - - - + + + - - - - - - - - - - - - - - + + - + + + + + + - - - + + + - - - + + + + + + + + + + + + + + + + + - - - - + + + + + + + + + + + + + + - - - - - - - - - - - - - + + + + + + + + + + - - - - - - - - - - - - + + + + + + + + + + + - - - - - - - - - - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + - - - - - - + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + - + diff --git a/PocketMC.App/Views/DashboardView.axaml.cs b/PocketMC.App/Views/DashboardView.axaml.cs index 79e8ca3..788a686 100755 --- a/PocketMC.App/Views/DashboardView.axaml.cs +++ b/PocketMC.App/Views/DashboardView.axaml.cs @@ -1,4 +1,3 @@ -using System; using Avalonia.Controls; namespace PocketMC.App.Views @@ -9,123 +8,5 @@ public DashboardView() { InitializeComponent(); } - - private void OnSizeChanged(object? sender, SizeChangedEventArgs e) - { - // Fail-safe check during early initialization stages - if (RootGrid == null || SidebarBorder == null || MainAreaGrid == null || - TopCardGrid == null || TopControlsPanel == null || MiddleGrid == null || - CpuCardBorder == null || RamCardBorder == null || BottomGrid == null || - NetworkCardBorder == null || PlayersCardBorder == null) - { - return; - } - - var width = e.NewSize.Width; - - // Calculate the actual available width for the server details dashboard area - // Sidebar is 250px + 16px spacing = 266px width - double mainWidth = (width >= 750) ? (width - 266) : width; - - // 1. Root Grid sidebar layout reflow - if (width < 750) - { - // Stack sidebar on top of main content - RootGrid.ColumnDefinitions = ColumnDefinitions.Parse("*"); - RootGrid.RowDefinitions = RowDefinitions.Parse("Auto, 16, *"); - - Grid.SetColumn(SidebarBorder, 0); - Grid.SetRow(SidebarBorder, 0); - - Grid.SetColumn(MainAreaGrid, 0); - Grid.SetRow(MainAreaGrid, 2); - } - else - { - // Sidebar on the left, main content on the right - RootGrid.ColumnDefinitions = ColumnDefinitions.Parse("250, 16, *"); - RootGrid.RowDefinitions = RowDefinitions.Parse("*"); - - Grid.SetColumn(SidebarBorder, 0); - Grid.SetRow(SidebarBorder, 0); - - Grid.SetColumn(MainAreaGrid, 2); - Grid.SetRow(MainAreaGrid, 0); - } - - // 2. Top Card Controls reflow (reflow actions underneath title when tight on space) - if (mainWidth < 780) - { - TopCardGrid.ColumnDefinitions = ColumnDefinitions.Parse("*"); - TopCardGrid.RowDefinitions = RowDefinitions.Parse("Auto, 12, Auto"); - - Grid.SetColumn(TopCardGrid.Children[0], 0); - Grid.SetRow(TopCardGrid.Children[0], 0); - - Grid.SetColumn(TopControlsPanel, 0); - Grid.SetRow(TopControlsPanel, 2); - TopControlsPanel.HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left; - } - else - { - TopCardGrid.ColumnDefinitions = ColumnDefinitions.Parse("*, Auto"); - TopCardGrid.RowDefinitions = RowDefinitions.Parse("*"); - - Grid.SetColumn(TopCardGrid.Children[0], 0); - Grid.SetRow(TopCardGrid.Children[0], 0); - - Grid.SetColumn(TopControlsPanel, 1); - Grid.SetRow(TopControlsPanel, 0); - TopControlsPanel.HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right; - } - - // 3. Middle Cards reflow (CPU and RAM side-by-side or stacked) - if (mainWidth < 680) - { - MiddleGrid.ColumnDefinitions = ColumnDefinitions.Parse("*"); - MiddleGrid.RowDefinitions = RowDefinitions.Parse("Auto, 16, Auto"); - - Grid.SetColumn(CpuCardBorder, 0); - Grid.SetRow(CpuCardBorder, 0); - - Grid.SetColumn(RamCardBorder, 0); - Grid.SetRow(RamCardBorder, 2); - } - else - { - MiddleGrid.ColumnDefinitions = ColumnDefinitions.Parse("*, 16, *"); - MiddleGrid.RowDefinitions = RowDefinitions.Parse("*"); - - Grid.SetColumn(CpuCardBorder, 0); - Grid.SetRow(CpuCardBorder, 0); - - Grid.SetColumn(RamCardBorder, 2); - Grid.SetRow(RamCardBorder, 0); - } - - // 4. Bottom Cards reflow (Network and Players side-by-side or stacked) - if (mainWidth < 680) - { - BottomGrid.ColumnDefinitions = ColumnDefinitions.Parse("*"); - BottomGrid.RowDefinitions = RowDefinitions.Parse("Auto, 16, Auto"); - - Grid.SetColumn(NetworkCardBorder, 0); - Grid.SetRow(NetworkCardBorder, 0); - - Grid.SetColumn(PlayersCardBorder, 0); - Grid.SetRow(PlayersCardBorder, 2); - } - else - { - BottomGrid.ColumnDefinitions = ColumnDefinitions.Parse("*, 16, *"); - BottomGrid.RowDefinitions = RowDefinitions.Parse("*"); - - Grid.SetColumn(NetworkCardBorder, 0); - Grid.SetRow(NetworkCardBorder, 0); - - Grid.SetColumn(PlayersCardBorder, 2); - Grid.SetRow(PlayersCardBorder, 0); - } - } } } diff --git a/PocketMC.App/Views/Dialogs/AppDialogWindow.axaml b/PocketMC.App/Views/Dialogs/AppDialogWindow.axaml new file mode 100644 index 0000000..4ee6be5 --- /dev/null +++ b/PocketMC.App/Views/Dialogs/AppDialogWindow.axaml @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + diff --git a/PocketMC.App/Views/MainWindow.axaml.cs b/PocketMC.App/Views/MainWindow.axaml.cs index 92dff1f..1d372f3 100755 --- a/PocketMC.App/Views/MainWindow.axaml.cs +++ b/PocketMC.App/Views/MainWindow.axaml.cs @@ -1,49 +1,151 @@ +using System; using System.Runtime.InteropServices; using Avalonia; using Avalonia.Controls; using Avalonia.Input; +using Microsoft.Extensions.DependencyInjection; +using PocketMC.App.Services; using PocketMC.App.ViewModels; -namespace PocketMC.App.Views +namespace PocketMC.App.Views; + +public partial class MainWindow : Window { - public partial class MainWindow : Window + public static readonly DirectProperty TitleBarContentMarginProperty = + AvaloniaProperty.RegisterDirect( + nameof(TitleBarContentMargin), + o => o.TitleBarContentMargin); + + private Thickness _titleBarContentMargin; + + public Thickness TitleBarContentMargin + { + get => _titleBarContentMargin; + private set => SetAndRaise(TitleBarContentMarginProperty, ref _titleBarContentMargin, value); + } + + public MainWindow() { - public static readonly DirectProperty TitleBarContentMarginProperty = - AvaloniaProperty.RegisterDirect( - nameof(TitleBarContentMargin), - o => o.TitleBarContentMargin); + InitializeComponent(); + TitleBarContentMargin = GetDefaultTitleBarMargin(); + } - private Thickness _titleBarContentMargin; + public MainWindow(MainWindowViewModel viewModel) : this() + { + DataContext = viewModel; + } - public Thickness TitleBarContentMargin + public static Thickness GetDefaultTitleBarMargin(OSPlatform? platform = null) + { + if (platform.HasValue) { - get => _titleBarContentMargin; - private set => SetAndRaise(TitleBarContentMarginProperty, ref _titleBarContentMargin, value); + if (platform.Value == OSPlatform.OSX) return new Thickness(80, 0, 0, 0); + if (platform.Value == OSPlatform.Linux) return new Thickness(0, 0, 0, 0); + return new Thickness(0, 0, 140, 0); } - // Parameterless constructor for XAML compiler / designer - public MainWindow() + if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + return new Thickness(80, 0, 0, 0); + } + + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + return new Thickness(0, 0, 0, 0); + } + + return new Thickness(0, 0, 140, 0); + } + + protected override void OnOpened(EventArgs e) + { + base.OnOpened(e); + + try + { + if (App.Services != null) + { + var accentService = App.Services.GetService(); + accentService?.ApplyCurrentAccent(); + + var wallpaperService = App.Services.GetService(); + wallpaperService?.Apply(WallpaperBlurLayer, WallpaperTintOverlay); + } + } + catch { - InitializeComponent(); + // Non-critical visual fallback } + } + + private void TitleBar_OnPointerPressed(object? sender, PointerPressedEventArgs e) + { + BeginMoveDrag(e); + } - public MainWindow(MainWindowViewModel viewModel) : this() + protected override void OnKeyDown(KeyEventArgs e) + { + var vm = DataContext as MainWindowViewModel; + + // Escape: Back navigation + if (e.Key == Key.Escape) { - if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + if (vm != null && vm.CanNavigateBack) { - TitleBarContentMargin = new Thickness(80, 0, 0, 0); + vm.NavigateBackCommand.Execute(null); + e.Handled = true; + return; } - else + } + // Alt+Left: Back navigation + else if (e.Key == Key.Left && e.KeyModifiers.HasFlag(KeyModifiers.Alt)) + { + if (vm != null && vm.CanNavigateBack) { - TitleBarContentMargin = new Thickness(0, 0, 140, 0); + vm.NavigateBackCommand.Execute(null); + e.Handled = true; + return; } - - DataContext = viewModel; } - - private void TitleBar_OnPointerPressed(object? sender, PointerPressedEventArgs e) + // Alt+Right: Forward navigation + else if (e.Key == Key.Right && e.KeyModifiers.HasFlag(KeyModifiers.Alt)) { - BeginMoveDrag(e); + if (vm != null && vm.CanNavigateForward) + { + vm.NavigateForwardCommand.Execute(null); + e.Handled = true; + return; + } + } + // Ctrl+1: Dashboard + else if (e.Key == Key.D1 && e.KeyModifiers.HasFlag(KeyModifiers.Control)) + { + vm?.NavigateDashboardCommand.Execute(null); + e.Handled = true; + return; + } + // Ctrl+2: Tunnel + else if (e.Key == Key.D2 && e.KeyModifiers.HasFlag(KeyModifiers.Control)) + { + vm?.NavigateTunnelCommand.Execute(null); + e.Handled = true; + return; } + // Ctrl+3: Remote Control + else if (e.Key == Key.D3 && e.KeyModifiers.HasFlag(KeyModifiers.Control)) + { + vm?.NavigateRemoteControlCommand.Execute(null); + e.Handled = true; + return; + } + // Ctrl+7: News + else if (e.Key == Key.D7 && e.KeyModifiers.HasFlag(KeyModifiers.Control)) + { + vm?.NavigateNewsCommand.Execute(null); + e.Handled = true; + return; + } + + base.OnKeyDown(e); } } diff --git a/PocketMC.App/Views/Marketplace/MapBrowserPage.axaml b/PocketMC.App/Views/Marketplace/MapBrowserPage.axaml new file mode 100644 index 0000000..235142e --- /dev/null +++ b/PocketMC.App/Views/Marketplace/MapBrowserPage.axaml @@ -0,0 +1,157 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/PocketMC.App/Views/Marketplace/MapBrowserPage.axaml.cs b/PocketMC.App/Views/Marketplace/MapBrowserPage.axaml.cs new file mode 100644 index 0000000..c431760 --- /dev/null +++ b/PocketMC.App/Views/Marketplace/MapBrowserPage.axaml.cs @@ -0,0 +1,12 @@ +using Avalonia.Controls; + +namespace PocketMC.App.Views.Marketplace +{ + public partial class MapBrowserPage : UserControl + { + public MapBrowserPage() + { + InitializeComponent(); + } + } +} diff --git a/PocketMC.App/Views/Marketplace/PluginBrowserPage.axaml b/PocketMC.App/Views/Marketplace/PluginBrowserPage.axaml new file mode 100644 index 0000000..d0e270b --- /dev/null +++ b/PocketMC.App/Views/Marketplace/PluginBrowserPage.axaml @@ -0,0 +1,157 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/PocketMC.App/Views/Marketplace/PluginBrowserPage.axaml.cs b/PocketMC.App/Views/Marketplace/PluginBrowserPage.axaml.cs new file mode 100644 index 0000000..7429f33 --- /dev/null +++ b/PocketMC.App/Views/Marketplace/PluginBrowserPage.axaml.cs @@ -0,0 +1,12 @@ +using Avalonia.Controls; + +namespace PocketMC.App.Views.Marketplace +{ + public partial class PluginBrowserPage : UserControl + { + public PluginBrowserPage() + { + InitializeComponent(); + } + } +} diff --git a/PocketMC.App/Views/Networking/PortConflictWindow.axaml b/PocketMC.App/Views/Networking/PortConflictWindow.axaml new file mode 100644 index 0000000..c60471a --- /dev/null +++ b/PocketMC.App/Views/Networking/PortConflictWindow.axaml @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - + - - - - + @@ -34,8 +58,8 @@ - - - + + + - - + + - - + + - + - + - - + + - + - + - + - + - + - + - - - + + + - - + + - - + + - + - - + + - - + + - - + + - + - + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/PocketMC.App/Views/NewsPage.axaml.cs b/PocketMC.App/Views/NewsPage.axaml.cs new file mode 100644 index 0000000..f4884f5 --- /dev/null +++ b/PocketMC.App/Views/NewsPage.axaml.cs @@ -0,0 +1,18 @@ +using Avalonia.Controls; +using PocketMC.App.ViewModels; + +namespace PocketMC.App.Views +{ + public partial class NewsPage : UserControl + { + public NewsPage() + { + InitializeComponent(); + } + + public NewsPage(NewsViewModel viewModel) : this() + { + DataContext = viewModel; + } + } +} diff --git a/PocketMC.App/Views/PlayerManagementPage.axaml.cs b/PocketMC.App/Views/PlayerManagementPage.axaml.cs index 064ae7f..73df544 100755 --- a/PocketMC.App/Views/PlayerManagementPage.axaml.cs +++ b/PocketMC.App/Views/PlayerManagementPage.axaml.cs @@ -8,5 +8,10 @@ public PlayerManagementPage() { InitializeComponent(); } + + public PlayerManagementPage(PocketMC.App.ViewModels.PlayerManagementViewModel viewModel) : this() + { + DataContext = viewModel; + } } } diff --git a/PocketMC.App/Views/PortsMapPage.axaml b/PocketMC.App/Views/PortsMapPage.axaml new file mode 100644 index 0000000..a032994 --- /dev/null +++ b/PocketMC.App/Views/PortsMapPage.axaml @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/PocketMC.App/Views/PortsMapPage.axaml.cs b/PocketMC.App/Views/PortsMapPage.axaml.cs new file mode 100644 index 0000000..bcfe0a2 --- /dev/null +++ b/PocketMC.App/Views/PortsMapPage.axaml.cs @@ -0,0 +1,27 @@ +using Avalonia.Controls; +using PocketMC.App.ViewModels; + +namespace PocketMC.App.Views +{ + public partial class PortsMapPage : UserControl + { + public PortsMapPage() + { + InitializeComponent(); + } + + public PortsMapPage(PortsMapViewModel viewModel) : this() + { + DataContext = viewModel; + } + + protected override async void OnLoaded(Avalonia.Interactivity.RoutedEventArgs e) + { + base.OnLoaded(e); + if (DataContext is PortsMapViewModel vm) + { + await vm.RefreshMapAsync(); + } + } + } +} diff --git a/PocketMC.App/Views/RemoteControlPage.axaml b/PocketMC.App/Views/RemoteControlPage.axaml index ed3a5e4..d61a5be 100755 --- a/PocketMC.App/Views/RemoteControlPage.axaml +++ b/PocketMC.App/Views/RemoteControlPage.axaml @@ -3,154 +3,274 @@ xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:vm="using:PocketMC.App.ViewModels" + xmlns:models="using:PocketMC.Core.Models" xmlns:lucide="using:Lucide.Avalonia" - mc:Ignorable="d" d:DesignWidth="850" d:DesignHeight="650" + mc:Ignorable="d" d:DesignWidth="900" d:DesignHeight="750" x:Class="PocketMC.App.Views.RemoteControlPage" - x:DataType="vm:RemoteControlViewModel"> + x:DataType="vm:RemoteControlViewModel" + x:CompileBindings="True"> - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + - - + + - - - - - - - - - - - - + + - - - - - - - - + + + + + + - + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + - - + + + + + + + + + + + + + - - - - - - + + + + + + + + + + + + + + Padding="12"> - + - + - + - - + - - + + - + @@ -101,38 +147,28 @@ - - - - - - - - - + + diff --git a/PocketMC.App/Views/ServerConsolePage.axaml.cs b/PocketMC.App/Views/ServerConsolePage.axaml.cs index aced2e0..8fe1b83 100755 --- a/PocketMC.App/Views/ServerConsolePage.axaml.cs +++ b/PocketMC.App/Views/ServerConsolePage.axaml.cs @@ -32,6 +32,11 @@ public ServerConsolePage() }; } + public ServerConsolePage(ServerConsoleViewModel viewModel) : this() + { + DataContext = viewModel; + } + private void OnLogLinesChanged(object? sender, NotifyCollectionChangedEventArgs e) { if (_boundViewModel != null && _boundViewModel.AutoScroll) diff --git a/PocketMC.App/Views/ServerSettingsPage.axaml b/PocketMC.App/Views/ServerSettingsPage.axaml index 3d7ad75..f117c38 100755 --- a/PocketMC.App/Views/ServerSettingsPage.axaml +++ b/PocketMC.App/Views/ServerSettingsPage.axaml @@ -1,12 +1,17 @@ + + + +