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