Compare commits
27 Commits
ae7e5096fc
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 1c3b8963ac | |||
| e915892fa2 | |||
| ab1aefd619 | |||
| 459b3f09f9 | |||
| 9bcdfd88e6 | |||
| 2dc472c85a | |||
| 2087c14285 | |||
| ef36fb5584 | |||
| d6bd7b9ef0 | |||
| 23195bd7c7 | |||
| 5e439ee8d5 | |||
| cbfd5f8da8 | |||
| da58c11e59 | |||
| 23ec6dd194 | |||
| 679d89b4b0 | |||
| 228b3bc55f | |||
| 7882bb9bfd | |||
| 968ff99987 | |||
| e5deb3f3d4 | |||
| 2c780afea8 | |||
| d141ec23dc | |||
| e24ee815bc | |||
| 372fa5eda2 | |||
| 631f5c9126 | |||
| cb85b132c3 | |||
| 1f663902e2 | |||
| 612976dfe6 |
1
.gitignore
vendored
@@ -17,6 +17,7 @@
|
|||||||
.idea/
|
.idea/
|
||||||
.editorconfig
|
.editorconfig
|
||||||
*.user
|
*.user
|
||||||
|
*.DotSettings
|
||||||
|
|
||||||
#backups
|
#backups
|
||||||
.old*/
|
.old*/
|
||||||
83
Mlaumcherb.Client.Avalonia/Config.cs
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
using Mlaumcherb.Client.Avalonia.зримое;
|
||||||
|
using Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
using Mlaumcherb.Client.Avalonia.сеть.Update;
|
||||||
|
using Mlaumcherb.Client.Avalonia.холопы;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia;
|
||||||
|
|
||||||
|
public record Config
|
||||||
|
{
|
||||||
|
[JsonRequired] public string config_version { get; set; } = "1.0.0";
|
||||||
|
public bool debug { get; set; } =
|
||||||
|
#if DEBUG
|
||||||
|
true;
|
||||||
|
#else
|
||||||
|
false;
|
||||||
|
#endif
|
||||||
|
public string player_name { get; set; } = "";
|
||||||
|
public int max_memory { get; set; } = 4096;
|
||||||
|
public string minecraft_dir { get; set; } = ".";
|
||||||
|
public bool download_java { get; set; } = true;
|
||||||
|
public bool redirect_game_output { get; set; } = false;
|
||||||
|
public string? last_launched_version { get; set; }
|
||||||
|
public int max_parallel_downloads { get; set; } = 16;
|
||||||
|
public GameVersionCatalogProps[] version_catalogs { get; set; } =
|
||||||
|
[
|
||||||
|
new() { name = "Тимериховое", url = "https://timerix.ddns.net/minecraft/catalog.json" },
|
||||||
|
new() { name = "Mojang", url = "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json" },
|
||||||
|
];
|
||||||
|
|
||||||
|
public UpdateHelper.GiteaConfig gitea { get; set; } = new()
|
||||||
|
{
|
||||||
|
serverUrl = "https://timerix.ddns.net/git/",
|
||||||
|
user = "Timerix",
|
||||||
|
repo = "mlaumcherb",
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
[JsonIgnore] private static IOPath _filePath = "млаумчерб.json";
|
||||||
|
|
||||||
|
public static Config LoadFromFile()
|
||||||
|
{
|
||||||
|
LauncherApp.Logger.LogDebug(nameof(Config), $"loading config from file '{_filePath}'");
|
||||||
|
if(!File.Exists(_filePath))
|
||||||
|
{
|
||||||
|
LauncherApp.Logger.LogDebug(nameof(Config), "file doesn't exist");
|
||||||
|
return new Config();
|
||||||
|
}
|
||||||
|
|
||||||
|
string text = File.ReadAllText(_filePath);
|
||||||
|
string errorMessage = "config is empty";
|
||||||
|
Config? config = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
config = JsonConvert.DeserializeObject<Config>(text);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
errorMessage = ex.Message;
|
||||||
|
}
|
||||||
|
if (config == null)
|
||||||
|
{
|
||||||
|
IOPath _brokenPath = _filePath + ".broken";
|
||||||
|
File.Move(_filePath, _brokenPath, true);
|
||||||
|
ErrorHelper.ShowMessageBox(nameof(Config),
|
||||||
|
$"Can't reed config file '{_filePath}'.\n" +
|
||||||
|
$"New config file has been created. Old is renamed to '{_brokenPath}'.\n\n" +
|
||||||
|
$"Config parser error: {errorMessage}");
|
||||||
|
config = new Config();
|
||||||
|
config.SaveToFile();
|
||||||
|
}
|
||||||
|
|
||||||
|
LauncherApp.Logger.LogDebug(nameof(Config), $"config has been loaded: {config}");
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SaveToFile()
|
||||||
|
{
|
||||||
|
LauncherApp.Logger.LogDebug(nameof(Config), $"saving config to file '{_filePath}'");
|
||||||
|
var text = JsonConvert.SerializeObject(this, Formatting.Indented);
|
||||||
|
File.WriteAllText(_filePath, text);
|
||||||
|
LauncherApp.Logger.LogDebug(nameof(Config), $"config has been saved: {text}");
|
||||||
|
}
|
||||||
|
}
|
||||||
191
Mlaumcherb.Client.Avalonia/GameVersion.cs
Normal file
@@ -0,0 +1,191 @@
|
|||||||
|
using System.Linq;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using CliWrap;
|
||||||
|
using DTLib.Extensions;
|
||||||
|
using Mlaumcherb.Client.Avalonia.зримое;
|
||||||
|
using Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
using Mlaumcherb.Client.Avalonia.сеть;
|
||||||
|
using Mlaumcherb.Client.Avalonia.сеть.TaskFactories;
|
||||||
|
using Mlaumcherb.Client.Avalonia.холопы;
|
||||||
|
using static Mlaumcherb.Client.Avalonia.холопы.PathHelper;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia;
|
||||||
|
|
||||||
|
public class GameVersion
|
||||||
|
{
|
||||||
|
private readonly InstalledGameVersionProps _props;
|
||||||
|
public string Id => _props.Id;
|
||||||
|
public IOPath WorkingDirectory { get; }
|
||||||
|
|
||||||
|
private IOPath JavaExecutableFilePath;
|
||||||
|
|
||||||
|
private GameVersionDescriptor _descriptor;
|
||||||
|
private JavaArguments _javaArgs;
|
||||||
|
private GameArguments _gameArgs;
|
||||||
|
private Libraries _libraries;
|
||||||
|
private CancellationTokenSource? _gameCts;
|
||||||
|
private CommandTask<CommandResult>? _commandTask;
|
||||||
|
|
||||||
|
internal GameVersion(InstalledGameVersionProps props, GameVersionDescriptor descriptor)
|
||||||
|
{
|
||||||
|
_props = props;
|
||||||
|
_descriptor = descriptor;
|
||||||
|
_javaArgs = new JavaArguments(_descriptor);
|
||||||
|
_gameArgs = new GameArguments(_descriptor);
|
||||||
|
_libraries = new Libraries(_descriptor);
|
||||||
|
WorkingDirectory = GetVersionDir(_descriptor.id);
|
||||||
|
JavaExecutableFilePath = GetJavaExecutablePath(
|
||||||
|
_descriptor.javaVersion.component, LauncherApp.Config.redirect_game_output);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task Download(bool checkHashes, Action<NetworkTask> networkTaskCreatedCallback)
|
||||||
|
{
|
||||||
|
LauncherApp.Logger.LogInfo(Id, $"started updating version {Id}");
|
||||||
|
|
||||||
|
List<INetworkTaskFactory> taskFactories =
|
||||||
|
[
|
||||||
|
new AssetsDownloadTaskFactory(_descriptor),
|
||||||
|
new LibrariesDownloadTaskFactory(_descriptor, _libraries),
|
||||||
|
];
|
||||||
|
if (LauncherApp.Config.download_java && (!File.Exists(JavaExecutableFilePath) || checkHashes))
|
||||||
|
taskFactories.Add(new JavaDownloadTaskFactory(_descriptor));
|
||||||
|
if (_descriptor.modpack != null)
|
||||||
|
taskFactories.Add(new ModpackDownloadTaskFactory(_descriptor));
|
||||||
|
// has to be downloaded last because it is used to check if version is installed
|
||||||
|
taskFactories.Add(new VersionJarDownloadTaskFactory(_descriptor));
|
||||||
|
|
||||||
|
var networkTasks = new List<NetworkTask>();
|
||||||
|
for (int i = 0; i < taskFactories.Count; i++)
|
||||||
|
{
|
||||||
|
var nt = await taskFactories[i].CreateAsync(checkHashes);
|
||||||
|
if (nt != null)
|
||||||
|
{
|
||||||
|
networkTasks.Add(nt);
|
||||||
|
networkTaskCreatedCallback.Invoke(nt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var nt in networkTasks)
|
||||||
|
{
|
||||||
|
await nt.StartAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
// create log4j config file
|
||||||
|
if (!File.Exists(GetLog4jConfigFilePath()))
|
||||||
|
{
|
||||||
|
await using var res = EmbeddedResources.GetResourceStream(
|
||||||
|
$"Mlaumcherb.Client.Avalonia.встроенное.{GetLog4jConfigFileName()}");
|
||||||
|
await using var file = File.OpenWrite(GetLog4jConfigFilePath());
|
||||||
|
await res.CopyToAsync(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
_props.IsInstalled = true;
|
||||||
|
LauncherApp.Logger.LogInfo(Id, $"finished updating version {Id}");
|
||||||
|
}
|
||||||
|
|
||||||
|
//minecraft player uuid explanation
|
||||||
|
//https://gist.github.com/CatDany/0e71ca7cd9b42a254e49/
|
||||||
|
//java uuid generation in c#
|
||||||
|
//https://stackoverflow.com/questions/18021808/uuid-interop-with-c-sharp-code
|
||||||
|
public static string GetPlayerUUID(string name)
|
||||||
|
{
|
||||||
|
byte[] name_bytes = Encoding.UTF8.GetBytes("OfflinePlayer:" + name);
|
||||||
|
var md5 = MD5.Create();
|
||||||
|
byte[] hash = md5.ComputeHash(name_bytes);
|
||||||
|
hash[6] &= 0x0f;
|
||||||
|
hash[6] |= 0x30;
|
||||||
|
hash[8] &= 0x3f;
|
||||||
|
hash[8] |= 0x80;
|
||||||
|
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
for (int i = 0; i < hash.Length; i++)
|
||||||
|
sb.Append(hash[i].ToString("x2"));
|
||||||
|
sb.Insert(8, '-').Insert(13, '-').Insert(18, '-').Insert(23, '-');
|
||||||
|
return sb.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task Launch()
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(LauncherApp.Config.player_name))
|
||||||
|
throw new Exception("invalid player name");
|
||||||
|
|
||||||
|
string classSeparator = PlatformHelper.GetOs() == "windows" ? ";" : ":";
|
||||||
|
Directory.Create(WorkingDirectory);
|
||||||
|
string uuid = GetPlayerUUID(LauncherApp.Config.player_name);
|
||||||
|
Dictionary<string, string> placeholder_values = new() {
|
||||||
|
{ "resolution_width", "1600" },
|
||||||
|
{ "resolution_height", "900" },
|
||||||
|
{ "xms", LauncherApp.Config.max_memory.ToString() },
|
||||||
|
{ "xmx", LauncherApp.Config.max_memory.ToString() },
|
||||||
|
{ "auth_player_name", LauncherApp.Config.player_name },
|
||||||
|
{ "auth_access_token", uuid },
|
||||||
|
{ "auth_session", $"token:{uuid}:{uuid}" },
|
||||||
|
{ "auth_xuid", "" },
|
||||||
|
{ "auth_uuid", uuid },
|
||||||
|
{ "clientid", "" },
|
||||||
|
{ "user_properties", "{}" },
|
||||||
|
{ "user_type", "userType" },
|
||||||
|
{ "launcher_name", "java-minecraft-launcher" },
|
||||||
|
{ "launcher_version", "1.6.84-j" },
|
||||||
|
{ "classpath", _libraries.Libs.Select(l => l.jarFilePath)
|
||||||
|
.Append(GetVersionJarFilePath(_descriptor.id))
|
||||||
|
.MergeToString(classSeparator) },
|
||||||
|
{ "assets_index_name", _descriptor.assets },
|
||||||
|
{ "assets_root", GetAssetsDir().ToString() },
|
||||||
|
{ "game_assets", GetAssetsDir().ToString() },
|
||||||
|
{ "game_directory", WorkingDirectory.ToString() },
|
||||||
|
{ "natives_directory", GetNativeLibrariesDir(_descriptor.id).ToString() },
|
||||||
|
{ "library_directory", GetLibrariesDir().ToString() },
|
||||||
|
{ "classpath_separator", classSeparator},
|
||||||
|
{ "path", GetLog4jConfigFilePath().ToString() },
|
||||||
|
{ "version_name", _descriptor.id },
|
||||||
|
{ "version_type", _descriptor.type },
|
||||||
|
{ "arch", PlatformHelper.GetArchOld() },
|
||||||
|
// { "quickPlayMultiplayer", "" },
|
||||||
|
// { "quickPlayPath", "" },
|
||||||
|
// { "quickPlayRealms", "" },
|
||||||
|
// { "quickPlaySingleplayer", "" },
|
||||||
|
{ "client_jar", GetVersionJarFilePath(_descriptor.id).ToString() },
|
||||||
|
};
|
||||||
|
|
||||||
|
List<string> argsList = new();
|
||||||
|
argsList.AddRange(_javaArgs.FillPlaceholders(placeholder_values));
|
||||||
|
argsList.Add(_descriptor.mainClass);
|
||||||
|
argsList.AddRange(_gameArgs.FillPlaceholders(placeholder_values));
|
||||||
|
var command = Cli.Wrap(JavaExecutableFilePath.ToString())
|
||||||
|
.WithWorkingDirectory(WorkingDirectory.ToString())
|
||||||
|
.WithArguments(argsList)
|
||||||
|
.WithValidation(CommandResultValidation.None);
|
||||||
|
if (LauncherApp.Config.redirect_game_output)
|
||||||
|
{
|
||||||
|
command = command
|
||||||
|
.WithStandardOutputPipe(PipeTarget.ToDelegate(LogGameOut))
|
||||||
|
.WithStandardErrorPipe(PipeTarget.ToDelegate(LogGameError));
|
||||||
|
}
|
||||||
|
LauncherApp.Logger.LogInfo(Id, "launching the game");
|
||||||
|
LauncherApp.Logger.LogDebug(Id, "java: " + command.TargetFilePath);
|
||||||
|
LauncherApp.Logger.LogDebug(Id, "working_dir: " + command.WorkingDirPath);
|
||||||
|
LauncherApp.Logger.LogDebug(Id, "arguments: \n\t" + argsList.MergeToString("\n\t"));
|
||||||
|
_gameCts = new();
|
||||||
|
_commandTask = command.ExecuteAsync(_gameCts.Token);
|
||||||
|
var result = await _commandTask;
|
||||||
|
LauncherApp.Logger.LogInfo(Id, $"game exited with code {result.ExitCode}");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void LogGameOut(string line)
|
||||||
|
{
|
||||||
|
LauncherApp.Logger.LogInfo(Id, line);
|
||||||
|
}
|
||||||
|
private void LogGameError(string line)
|
||||||
|
{
|
||||||
|
LauncherApp.Logger.LogWarn(Id, line);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Close()
|
||||||
|
{
|
||||||
|
_gameCts?.Cancel();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public override string ToString() => Id;
|
||||||
|
}
|
||||||
@@ -1,15 +1,16 @@
|
|||||||
namespace Млаумчерб.Клиент;
|
namespace Mlaumcherb.Client.Avalonia;
|
||||||
|
|
||||||
public class LauncherLogger : ILogger
|
public class LauncherLogger : ILogger
|
||||||
{
|
{
|
||||||
private CompositeLogger _compositeLogger;
|
private CompositeLogger _compositeLogger;
|
||||||
private FileLogger _fileLogger;
|
private FileLogger _fileLogger;
|
||||||
public static readonly IOPath LogsDirectory = "launcher_logs";
|
public static readonly IOPath LogsDirectory = "launcher_logs";
|
||||||
public IOPath LogfileName => _fileLogger.LogfileName;
|
public IOPath LogFilePath => _fileLogger.LogfileName;
|
||||||
|
|
||||||
public LauncherLogger()
|
public LauncherLogger()
|
||||||
{
|
{
|
||||||
_fileLogger = new FileLogger(LogsDirectory, "млаумчерб");
|
_fileLogger = new FileLogger(LogsDirectory, "млаумчерб");
|
||||||
|
_fileLogger.DebugLogEnabled = true;
|
||||||
ILogger[] loggers =
|
ILogger[] loggers =
|
||||||
[
|
[
|
||||||
_fileLogger,
|
_fileLogger,
|
||||||
@@ -18,13 +19,11 @@ public class LauncherLogger : ILogger
|
|||||||
#endif
|
#endif
|
||||||
];
|
];
|
||||||
_compositeLogger = new CompositeLogger(loggers);
|
_compositeLogger = new CompositeLogger(loggers);
|
||||||
|
|
||||||
#if DEBUG
|
|
||||||
DebugLogEnabled = true;
|
|
||||||
#endif
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public delegate void LogHandler(string context, LogSeverity severity, object message, ILogFormat format);
|
public record LogMessage(string context, LogSeverity severity, object message, ILogFormat format);
|
||||||
|
|
||||||
|
public delegate void LogHandler(LogMessage msg);
|
||||||
public event LogHandler? OnLogMessage;
|
public event LogHandler? OnLogMessage;
|
||||||
|
|
||||||
public void Log(string context, LogSeverity severity, object message, ILogFormat format)
|
public void Log(string context, LogSeverity severity, object message, ILogFormat format)
|
||||||
@@ -39,7 +38,7 @@ public class LauncherLogger : ILogger
|
|||||||
_ => throw new ArgumentOutOfRangeException(nameof(severity), severity, null)
|
_ => throw new ArgumentOutOfRangeException(nameof(severity), severity, null)
|
||||||
};
|
};
|
||||||
if(isEnabled)
|
if(isEnabled)
|
||||||
OnLogMessage?.Invoke(context, severity, message, format);
|
OnLogMessage?.Invoke(new(context, severity, message, format));
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Dispose()
|
public void Dispose()
|
||||||
@@ -56,7 +55,11 @@ public class LauncherLogger : ILogger
|
|||||||
public bool DebugLogEnabled
|
public bool DebugLogEnabled
|
||||||
{
|
{
|
||||||
get => _compositeLogger.DebugLogEnabled;
|
get => _compositeLogger.DebugLogEnabled;
|
||||||
set => _compositeLogger.DebugLogEnabled = value;
|
set
|
||||||
|
{
|
||||||
|
_compositeLogger.DebugLogEnabled = value;
|
||||||
|
_fileLogger.DebugLogEnabled = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public bool InfoLogEnabled
|
public bool InfoLogEnabled
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
|
<Version>1.1.2</Version>
|
||||||
<OutputType Condition="'$(Configuration)' == 'Debug'">Exe</OutputType>
|
<OutputType Condition="'$(Configuration)' == 'Debug'">Exe</OutputType>
|
||||||
<OutputType Condition="'$(Configuration)' != 'Debug'">WinExe</OutputType>
|
<OutputType Condition="'$(Configuration)' != 'Debug'">WinExe</OutputType>
|
||||||
<TargetFramework>net8.0</TargetFramework>
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
@@ -11,40 +12,27 @@
|
|||||||
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
|
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
|
||||||
<ApplicationIcon>капитал\кубе.ico</ApplicationIcon>
|
<ApplicationIcon>капитал\кубе.ico</ApplicationIcon>
|
||||||
<AssemblyName>млаумчерб</AssemblyName>
|
<AssemblyName>млаумчерб</AssemblyName>
|
||||||
<Configurations>Release;Debug</Configurations>
|
|
||||||
<Platforms>x64</Platforms>
|
<Platforms>x64</Platforms>
|
||||||
|
<!-- AXAML resource has no public constructor -->
|
||||||
|
<NoWarn>AVLN3001</NoWarn>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Avalonia" Version="11.*" />
|
<PackageReference Include="Avalonia" Version="11.2.*" />
|
||||||
<PackageReference Include="Avalonia.Desktop" Version="11.*" />
|
<PackageReference Include="Avalonia.Desktop" Version="11.2.*" />
|
||||||
<PackageReference Include="Avalonia.Themes.Simple" Version="11.*" />
|
<PackageReference Include="Avalonia.Themes.Simple" Version="11.2.*" />
|
||||||
<PackageReference Condition="'$(Configuration)' == 'Debug'" Include="Avalonia.Diagnostics" Version="11.*" />
|
<PackageReference Condition="'$(Configuration)' == 'Debug'" Include="Avalonia.Diagnostics" Version="11.2.*" />
|
||||||
<PackageReference Include="Avalonia.Labs.Gif" Version="11.2.999-cibuild-00051673"/>
|
<PackageReference Include="Avalonia.Labs.Gif" Version="11.2.*" />
|
||||||
<PackageReference Include="CliWrap" Version="3.6.*" />
|
<PackageReference Include="CliWrap" Version="3.7.0" />
|
||||||
<PackageReference Include="DTLib" Version="1.4.3" />
|
<PackageReference Include="DTLib" Version="1.7.3" />
|
||||||
<PackageReference Include="MessageBox.Avalonia" Version="3.1.*" />
|
<PackageReference Include="LZMA-SDK" Version="22.1.1" />
|
||||||
|
<PackageReference Include="MessageBox.Avalonia" Version="3.2.0" />
|
||||||
<PackageReference Include="Newtonsoft.Json" Version="13.*" />
|
<PackageReference Include="Newtonsoft.Json" Version="13.*" />
|
||||||
<PackageReference Include="EasyCompressor.LZMA" Version="2.0.2" />
|
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<AvaloniaResource Include="капитал\**"/>
|
<AvaloniaResource Include="капитал\**"/>
|
||||||
</ItemGroup>
|
<EmbeddedResource Include="встроенное\**" />
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<Compile Update="видимое\VersionItemView.axaml.cs">
|
|
||||||
<DependentUpon>VersionItemView.axaml</DependentUpon>
|
|
||||||
<SubType>Code</SubType>
|
|
||||||
</Compile>
|
|
||||||
<Compile Update="видимое\Окне.axaml.cs">
|
|
||||||
<DependentUpon>Окне.axaml</DependentUpon>
|
|
||||||
<SubType>Code</SubType>
|
|
||||||
</Compile>
|
|
||||||
<Compile Update="видимое\Приложение.axaml.cs">
|
|
||||||
<DependentUpon>Приложение.axaml</DependentUpon>
|
|
||||||
<SubType>Code</SubType>
|
|
||||||
</Compile>
|
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
@@ -6,6 +6,7 @@ global using System.Text;
|
|||||||
global using System.Threading;
|
global using System.Threading;
|
||||||
global using System.Threading.Tasks;
|
global using System.Threading.Tasks;
|
||||||
global using Newtonsoft.Json;
|
global using Newtonsoft.Json;
|
||||||
|
global using DTLib;
|
||||||
global using DTLib.Logging;
|
global using DTLib.Logging;
|
||||||
global using DTLib.Filesystem;
|
global using DTLib.Filesystem;
|
||||||
global using File = DTLib.Filesystem.File;
|
global using File = DTLib.Filesystem.File;
|
||||||
@@ -13,11 +14,11 @@ global using Directory = DTLib.Filesystem.Directory;
|
|||||||
global using Path = DTLib.Filesystem.Path;
|
global using Path = DTLib.Filesystem.Path;
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using Avalonia;
|
using Avalonia;
|
||||||
using Млаумчерб.Клиент.видимое;
|
using Mlaumcherb.Client.Avalonia.зримое;
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент;
|
namespace Mlaumcherb.Client.Avalonia;
|
||||||
|
|
||||||
public class Главне
|
public class Program
|
||||||
{
|
{
|
||||||
[STAThread]
|
[STAThread]
|
||||||
public static void Main(string[] args)
|
public static void Main(string[] args)
|
||||||
@@ -30,13 +31,13 @@ public class Главне
|
|||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Приложение.Логгер.LogError(nameof(Главне), ex);
|
LauncherApp.Logger.LogError(nameof(Program), ex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Avalonia configuration, don't remove; also used by visual designer.
|
// Avalonia configuration, don't remove; also used by visual designer.
|
||||||
public static AppBuilder BuildAvaloniaApp()
|
public static AppBuilder BuildAvaloniaApp()
|
||||||
=> AppBuilder.Configure<Приложение>()
|
=> AppBuilder.Configure<LauncherApp>()
|
||||||
.UsePlatformDetect()
|
.UsePlatformDetect()
|
||||||
.LogToTrace();
|
.LogToTrace();
|
||||||
}
|
}
|
||||||
28
Mlaumcherb.Client.Avalonia/встроенное/log4j.xml
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
<Configuration status="WARN" packages="com.mojang.util">
|
||||||
|
<Appenders>
|
||||||
|
<Console name="SysOut" target="SYSTEM_OUT">
|
||||||
|
<PatternLayout pattern="[%d{HH:mm:ss}] [%t/%level]: %msg%n"/>
|
||||||
|
</Console>
|
||||||
|
<Queue name="ServerGuiConsole">
|
||||||
|
<PatternLayout pattern="[%d{HH:mm:ss} %level]: %msg%n"/>
|
||||||
|
</Queue>
|
||||||
|
<RollingRandomAccessFile name="File" fileName="logs/latest.log" filePattern="logs/%d{yyyy-MM-dd}-%i.log.gz">
|
||||||
|
<PatternLayout pattern="[%d{HH:mm:ss}] [%t/%level]: %msg%n"/>
|
||||||
|
<Policies>
|
||||||
|
<TimeBasedTriggeringPolicy/>
|
||||||
|
<OnStartupTriggeringPolicy/>
|
||||||
|
</Policies>
|
||||||
|
</RollingRandomAccessFile>
|
||||||
|
</Appenders>
|
||||||
|
<Loggers>
|
||||||
|
<Root level="info">
|
||||||
|
<filters>
|
||||||
|
<MarkerFilter marker="NETWORK_PACKETS" onMatch="DENY" onMismatch="NEUTRAL"/>
|
||||||
|
<RegexFilter regex="(?s).*\$\{[^}]*\}.*" onMatch="DENY" onMismatch="NEUTRAL"/>
|
||||||
|
</filters>
|
||||||
|
<AppenderRef ref="SysOut"/>
|
||||||
|
<AppenderRef ref="File"/>
|
||||||
|
<AppenderRef ref="ServerGuiConsole"/>
|
||||||
|
</Root>
|
||||||
|
</Loggers>
|
||||||
|
</Configuration>
|
||||||
26
Mlaumcherb.Client.Avalonia/зримое/DownloadItemView.axaml
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
<UserControl xmlns="https://github.com/avaloniaui"
|
||||||
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
|
x:Class="Mlaumcherb.Client.Avalonia.зримое.NetworkTaskView"
|
||||||
|
Padding="4" MinHeight="90" MinWidth="200"
|
||||||
|
VerticalAlignment="Top"
|
||||||
|
HorizontalAlignment="Stretch"
|
||||||
|
BorderThickness="1" BorderBrush="#999999">
|
||||||
|
<Grid RowDefinitions="* * *" ColumnDefinitions="* 30">
|
||||||
|
<TextBlock Name="NameText"
|
||||||
|
Grid.Row="0" Grid.Column="0" />
|
||||||
|
<Button Grid.Row="0" Grid.Column="1"
|
||||||
|
Classes="button_no_border"
|
||||||
|
Background="Transparent"
|
||||||
|
Foreground="#FF4040"
|
||||||
|
FontSize="12"
|
||||||
|
Click="RemoveFromList">
|
||||||
|
[X]
|
||||||
|
</Button>
|
||||||
|
<TextBlock Name="StatusText"
|
||||||
|
Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2"
|
||||||
|
FontSize="15"/>
|
||||||
|
<TextBlock Name="ProgressText"
|
||||||
|
Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2"
|
||||||
|
FontSize="14"/>
|
||||||
|
</Grid>
|
||||||
|
</UserControl>
|
||||||
66
Mlaumcherb.Client.Avalonia/зримое/DownloadItemView.axaml.cs
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
using Avalonia.Controls;
|
||||||
|
using Avalonia.Interactivity;
|
||||||
|
using Avalonia.Threading;
|
||||||
|
using Mlaumcherb.Client.Avalonia.сеть;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.зримое;
|
||||||
|
|
||||||
|
public partial class NetworkTaskView : UserControl
|
||||||
|
{
|
||||||
|
public readonly NetworkTask Task;
|
||||||
|
private readonly Action<NetworkTaskView> _removeFromList;
|
||||||
|
|
||||||
|
|
||||||
|
public NetworkTaskView()
|
||||||
|
{
|
||||||
|
throw new Exception();
|
||||||
|
}
|
||||||
|
|
||||||
|
public NetworkTaskView(NetworkTask task, Action<NetworkTaskView> removeFromList)
|
||||||
|
{
|
||||||
|
Task = task;
|
||||||
|
_removeFromList = removeFromList;
|
||||||
|
InitializeComponent();
|
||||||
|
NameText.Text = task.Name;
|
||||||
|
StatusText.Text = task.DownloadStatus.ToString();
|
||||||
|
task.OnStart += OnTaskOnStart;
|
||||||
|
task.OnProgress += ReportProgress;
|
||||||
|
task.OnStop += OnTaskStop;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnTaskOnStart()
|
||||||
|
{
|
||||||
|
Dispatcher.UIThread.Invoke(() =>
|
||||||
|
{
|
||||||
|
StatusText.Text = Task.DownloadStatus.ToString();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnTaskStop(NetworkTask.Status status)
|
||||||
|
{
|
||||||
|
Dispatcher.UIThread.Invoke(() =>
|
||||||
|
{
|
||||||
|
StatusText.Text = status.ToString();
|
||||||
|
if(!string.IsNullOrEmpty(ProgressText.Text))
|
||||||
|
{
|
||||||
|
int speedIndex = ProgressText.Text.IndexOf('(');
|
||||||
|
if(speedIndex > 0)
|
||||||
|
ProgressText.Text = ProgressText.Text.Remove(speedIndex);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void ReportProgress(DownloadProgress progress)
|
||||||
|
{
|
||||||
|
Dispatcher.UIThread.Invoke(() =>
|
||||||
|
{
|
||||||
|
ProgressText.Text = progress.ToString();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RemoveFromList(object? sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
Task.Cancel();
|
||||||
|
Dispatcher.UIThread.Invoke(() => _removeFromList.Invoke(this));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,8 +2,9 @@
|
|||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||||
xmlns:local="clr-namespace:Млаумчерб.Клиент"
|
xmlns:local="clr-namespace:Mlaumcherb.Client.Avalonia"
|
||||||
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
|
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
|
||||||
x:Class="Млаумчерб.Клиент.видимое.VersionItemView">
|
x:Class="Mlaumcherb.Client.Avalonia.зримое.GameVersionItemView"
|
||||||
|
Padding="2">
|
||||||
<TextBlock Name="text" Background="Transparent"/>
|
<TextBlock Name="text" Background="Transparent"/>
|
||||||
</UserControl>
|
</UserControl>
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
using Avalonia.Controls;
|
||||||
|
using Avalonia.Media;
|
||||||
|
using Avalonia.Threading;
|
||||||
|
using Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.зримое;
|
||||||
|
|
||||||
|
public abstract partial class GameVersionItemView : ListBoxItem
|
||||||
|
{
|
||||||
|
private static readonly SolidColorBrush _avaliableColor = new(Color.FromRgb(30, 130, 40));
|
||||||
|
private static readonly SolidColorBrush _unavaliableColor = new(Color.FromRgb(170, 70, 70));
|
||||||
|
|
||||||
|
protected GameVersionItemView(string name, bool initialStatus)
|
||||||
|
{
|
||||||
|
InitializeComponent();
|
||||||
|
text.Text = name;
|
||||||
|
UpdateBackground(initialStatus);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void UpdateBackground(bool isInstalled)
|
||||||
|
{
|
||||||
|
Dispatcher.UIThread.Invoke(() => Background = isInstalled ? _avaliableColor : _unavaliableColor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Background changes when props status changes
|
||||||
|
public class InstalledGameVersionItemView : GameVersionItemView
|
||||||
|
{
|
||||||
|
public readonly InstalledGameVersionProps Props;
|
||||||
|
|
||||||
|
public InstalledGameVersionItemView(InstalledGameVersionProps props) : base(props.Id, props.IsInstalled)
|
||||||
|
{
|
||||||
|
Props = props;
|
||||||
|
props.StatusChanged += UpdateBackground;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Background is set once by checking if the version is present in InstalledVersionsCatalog
|
||||||
|
public class RemoteGameVersionItemView : GameVersionItemView
|
||||||
|
{
|
||||||
|
public readonly RemoteVersionDescriptorProps Props;
|
||||||
|
|
||||||
|
public RemoteGameVersionItemView(RemoteVersionDescriptorProps props)
|
||||||
|
: base(props.id, LauncherApp.InstalledVersionCatalog.versions.ContainsKey(props.id))
|
||||||
|
{
|
||||||
|
Props = props;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<Application xmlns="https://github.com/avaloniaui"
|
<Application xmlns="https://github.com/avaloniaui"
|
||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
x:Class="Млаумчерб.Клиент.видимое.Приложение"
|
x:Class="Mlaumcherb.Client.Avalonia.зримое.LauncherApp"
|
||||||
RequestedThemeVariant="Dark">
|
RequestedThemeVariant="Dark">
|
||||||
<Application.Styles>
|
<Application.Styles>
|
||||||
<SimpleTheme />
|
<SimpleTheme />
|
||||||
@@ -25,6 +25,10 @@
|
|||||||
<Setter Property="MinWidth" Value="50"/>
|
<Setter Property="MinWidth" Value="50"/>
|
||||||
</Style>
|
</Style>
|
||||||
|
|
||||||
|
<Style Selector="Button.button_dark">
|
||||||
|
<Setter Property="Background" Value="#65656070"/>
|
||||||
|
</Style>
|
||||||
|
|
||||||
<Style Selector="Border.menu_separator">
|
<Style Selector="Border.menu_separator">
|
||||||
<Setter Property="Background" Value="#ff505050"/>
|
<Setter Property="Background" Value="#ff505050"/>
|
||||||
<Setter Property="Width" Value="1"/>
|
<Setter Property="Width" Value="1"/>
|
||||||
75
Mlaumcherb.Client.Avalonia/зримое/LauncherApp.axaml.cs
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
using Avalonia;
|
||||||
|
using Avalonia.Controls.ApplicationLifetimes;
|
||||||
|
using Avalonia.Markup.Xaml;
|
||||||
|
using Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
using Mlaumcherb.Client.Avalonia.сеть.Update;
|
||||||
|
using Mlaumcherb.Client.Avalonia.холопы;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.зримое;
|
||||||
|
|
||||||
|
public class LauncherApp : Application
|
||||||
|
{
|
||||||
|
public static LauncherLogger Logger = new();
|
||||||
|
public static Config Config = null!;
|
||||||
|
public static InstalledVersionCatalog InstalledVersionCatalog = null!;
|
||||||
|
|
||||||
|
public override void Initialize()
|
||||||
|
{
|
||||||
|
Logger.LogInfo(nameof(LauncherApp), "приложение запущено");
|
||||||
|
Config = Config.LoadFromFile();
|
||||||
|
Logger.DebugLogEnabled = Config.debug;
|
||||||
|
AvaloniaXamlLoader.Load(this);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
SelfUpdateAsync();
|
||||||
|
|
||||||
|
// some file required by forge installer
|
||||||
|
if (!File.Exists("launcher_profiles.json"))
|
||||||
|
{
|
||||||
|
File.WriteAllText("launcher_profiles.json", "{}");
|
||||||
|
}
|
||||||
|
|
||||||
|
InstalledVersionCatalog = InstalledVersionCatalog.Load();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
ErrorHelper.ShowMessageBox(nameof(LauncherApp), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async void SelfUpdateAsync()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Logger.LogInfo(nameof(LauncherApp), "checking for updates...");
|
||||||
|
var upd = new UpdateHelper(Config.gitea);
|
||||||
|
upd.DeleteBackupFiles();
|
||||||
|
if (await upd.IsUpdateAvailable())
|
||||||
|
{
|
||||||
|
Logger.LogInfo(nameof(LauncherApp), "downloading update...");
|
||||||
|
await upd.UpdateSelf();
|
||||||
|
Logger.LogInfo(nameof(LauncherApp), "restarting...");
|
||||||
|
upd.RestartSelf();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Logger.LogInfo(nameof(LauncherApp), "no updates found");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
ErrorHelper.ShowMessageBox(nameof(LauncherApp), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnFrameworkInitializationCompleted()
|
||||||
|
{
|
||||||
|
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||||
|
{
|
||||||
|
desktop.MainWindow = new MainWindow();
|
||||||
|
}
|
||||||
|
|
||||||
|
base.OnFrameworkInitializationCompleted();
|
||||||
|
}
|
||||||
|
}
|
||||||
13
Mlaumcherb.Client.Avalonia/зримое/LogMessageView.axaml
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
<UserControl xmlns="https://github.com/avaloniaui"
|
||||||
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
|
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||||
|
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||||
|
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
|
||||||
|
x:Class="Mlaumcherb.Client.Avalonia.зримое.LogMessageView"
|
||||||
|
FontSize="14">
|
||||||
|
<SelectableTextBlock Name="ContentTextBox"
|
||||||
|
FontSize="{Binding $parent.FontSize}"
|
||||||
|
TextWrapping="Wrap"
|
||||||
|
VerticalAlignment="Top"
|
||||||
|
Background="Transparent"/>
|
||||||
|
</UserControl>
|
||||||
23
Mlaumcherb.Client.Avalonia/зримое/LogMessageView.axaml.cs
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
using Avalonia.Controls;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.зримое;
|
||||||
|
|
||||||
|
public partial class LogMessageView : UserControl
|
||||||
|
{
|
||||||
|
public static ILogFormat ShortLogFormat = new DefaultLogFormat
|
||||||
|
{
|
||||||
|
TimeStampFormat = MyTimeFormat.TimeOnly,
|
||||||
|
PrintContext = false
|
||||||
|
};
|
||||||
|
|
||||||
|
public LogMessageView()
|
||||||
|
{
|
||||||
|
throw new Exception();
|
||||||
|
}
|
||||||
|
|
||||||
|
public LogMessageView(LauncherLogger.LogMessage m)
|
||||||
|
{
|
||||||
|
InitializeComponent();
|
||||||
|
ContentTextBox.Text = ShortLogFormat.CreateMessage(m.context, m.severity, m.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
190
Mlaumcherb.Client.Avalonia/зримое/MainWindow.axaml
Normal file
@@ -0,0 +1,190 @@
|
|||||||
|
<Window xmlns="https://github.com/avaloniaui"
|
||||||
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
|
xmlns:gif="clr-namespace:Avalonia.Labs.Gif;assembly=Avalonia.Labs.Gif"
|
||||||
|
xmlns:local="clr-namespace:Mlaumcherb.Client.Avalonia"
|
||||||
|
x:Class="Mlaumcherb.Client.Avalonia.зримое.MainWindow"
|
||||||
|
Name="window"
|
||||||
|
Title="млаумчерб"
|
||||||
|
Icon="avares://млаумчерб/капитал/кубе.ico"
|
||||||
|
FontFamily="{StaticResource MonospaceFont}" FontSize="18"
|
||||||
|
MinWidth="800" MinHeight="400"
|
||||||
|
Width="800" Height="600"
|
||||||
|
WindowStartupLocation="CenterScreen">
|
||||||
|
<Grid RowDefinitions="* 30">
|
||||||
|
<Image Grid.RowSpan="2" Stretch="UniformToFill"
|
||||||
|
Source="avares://млаумчерб/капитал/фоне.png"/>
|
||||||
|
|
||||||
|
<Grid Grid.Row="0" Margin="10">
|
||||||
|
<Grid.ColumnDefinitions>
|
||||||
|
<ColumnDefinition MinWidth="150"/>
|
||||||
|
<ColumnDefinition Width="2" />
|
||||||
|
<ColumnDefinition MinWidth="300"/>
|
||||||
|
<ColumnDefinition Width="2" />
|
||||||
|
<ColumnDefinition MinWidth="150"/>
|
||||||
|
</Grid.ColumnDefinitions>
|
||||||
|
|
||||||
|
<GridSplitter Grid.Column="1" Background="Transparent" ResizeDirection="Columns" />
|
||||||
|
<GridSplitter Grid.Column="3" Background="Transparent" ResizeDirection="Columns"/>
|
||||||
|
|
||||||
|
<!-- Central panel -->
|
||||||
|
<Border Grid.Column="2"
|
||||||
|
Classes="dark_tr_bg white_border">
|
||||||
|
<Grid>
|
||||||
|
<Grid.RowDefinitions>* 60</Grid.RowDefinitions>
|
||||||
|
<ScrollViewer Grid.Row="0"
|
||||||
|
HorizontalScrollBarVisibility="Disabled"
|
||||||
|
VerticalScrollBarVisibility="Auto">
|
||||||
|
<StackPanel Margin="10" Spacing="6">
|
||||||
|
<TextBlock>Ник:</TextBlock>
|
||||||
|
<TextBox Background="Transparent"
|
||||||
|
Text="{Binding #window.PlayerName}"/>
|
||||||
|
|
||||||
|
<TextBlock>Версия игры:</TextBlock>
|
||||||
|
<ComboBox Name="InstalledVersionCatalogComboBox"/>
|
||||||
|
<Button Name="RescanInstalledVersionsButton"
|
||||||
|
Click="RescanInstalledVersionsButton_OnClick"
|
||||||
|
Classes="button_dark">
|
||||||
|
Обновить список
|
||||||
|
</Button>
|
||||||
|
<Button Name="DeleteVersionButton"
|
||||||
|
Click="DeleteVersionButton_OnClick"
|
||||||
|
Classes="button_dark">
|
||||||
|
Удалить версию
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Expander Header="Добавление версий"
|
||||||
|
BorderThickness="1" BorderBrush="Gray"
|
||||||
|
Padding="4">
|
||||||
|
<StackPanel Spacing="6">
|
||||||
|
<TextBlock>Источник:</TextBlock>
|
||||||
|
<ComboBox Name="RemoteVersionCatalogComboBox"/>
|
||||||
|
<WrapPanel>
|
||||||
|
<CheckBox Name="ReleaseVersionTypeCheckBox" IsChecked="True">релиз</CheckBox>
|
||||||
|
<CheckBox Name="SnapshotVersionTypeCheckBox">снапшот</CheckBox>
|
||||||
|
<CheckBox Name="OldVersionTypeCheckBox">старое</CheckBox>
|
||||||
|
<CheckBox Name="OtherVersionTypeAlphaCheckBox">другое</CheckBox>
|
||||||
|
</WrapPanel>
|
||||||
|
<Button Name="SearchVersionsButton"
|
||||||
|
Click="SearchVersionsButton_OnClick"
|
||||||
|
Classes="button_dark">
|
||||||
|
Поиск
|
||||||
|
</Button>
|
||||||
|
<TextBlock>Доступные версии:</TextBlock>
|
||||||
|
<ComboBox Name="RemoteVersionCatalogItemsComboBox"/>
|
||||||
|
<Button Name="AddVersionButton" IsEnabled="False"
|
||||||
|
Click="AddVersionButton_OnClick"
|
||||||
|
Classes="button_dark">
|
||||||
|
Добавить
|
||||||
|
</Button>
|
||||||
|
</StackPanel>
|
||||||
|
</Expander>
|
||||||
|
|
||||||
|
<TextBlock>
|
||||||
|
<Run>Выделенная память:</Run>
|
||||||
|
<TextBox Background="Transparent" Padding="0"
|
||||||
|
BorderThickness="1"
|
||||||
|
BorderBrush="#777777"
|
||||||
|
Text="{Binding #window.MemoryLimit}">
|
||||||
|
</TextBox>
|
||||||
|
<Run>Мб</Run>
|
||||||
|
</TextBlock>
|
||||||
|
<Slider Minimum="2048" Maximum="8192"
|
||||||
|
Value="{Binding #window.MemoryLimit}">
|
||||||
|
</Slider>
|
||||||
|
|
||||||
|
<CheckBox IsChecked="{Binding #window.UpdateGameFiles}">
|
||||||
|
Обновить файлы игры
|
||||||
|
</CheckBox>
|
||||||
|
<CheckBox IsChecked="{Binding #window.EnableJavaDownload}">
|
||||||
|
Скачивать джаву
|
||||||
|
</CheckBox>
|
||||||
|
<CheckBox IsChecked="{Binding #window.RedirectGameOutput}">
|
||||||
|
Выводить лог игры в лаунчер
|
||||||
|
</CheckBox>
|
||||||
|
</StackPanel>
|
||||||
|
</ScrollViewer>
|
||||||
|
<Button Name="LaunchButton" Grid.Row="1"
|
||||||
|
Margin="10" Padding="4"
|
||||||
|
Classes="button_no_border"
|
||||||
|
Background="#BBfd7300"
|
||||||
|
Click="Запуск">
|
||||||
|
Запуск
|
||||||
|
</Button>
|
||||||
|
</Grid>
|
||||||
|
</Border>
|
||||||
|
|
||||||
|
<!-- Left panel -->
|
||||||
|
<Border Grid.Column="0"
|
||||||
|
Classes="dark_tr_bg white_border">
|
||||||
|
<Grid RowDefinitions="36 *">
|
||||||
|
<Border Classes="white_border" Margin="-1" Padding="4">
|
||||||
|
<DockPanel>
|
||||||
|
<TextBlock FontWeight="Bold"
|
||||||
|
DockPanel.Dock="Left">
|
||||||
|
Лог
|
||||||
|
</TextBlock>
|
||||||
|
<Button Click="ClearLogPanel"
|
||||||
|
Classes="menu_button"
|
||||||
|
DockPanel.Dock="Right"
|
||||||
|
HorizontalAlignment="Right">
|
||||||
|
очистить
|
||||||
|
</Button>
|
||||||
|
</DockPanel>
|
||||||
|
</Border>
|
||||||
|
<ScrollViewer Name="LogScrollViewer" Grid.Row="1"
|
||||||
|
HorizontalScrollBarVisibility="Disabled"
|
||||||
|
VerticalScrollBarVisibility="Visible"
|
||||||
|
Background="Transparent">
|
||||||
|
<StackPanel Name="LogPanel"
|
||||||
|
VerticalAlignment="Top"/>
|
||||||
|
</ScrollViewer>
|
||||||
|
</Grid>
|
||||||
|
</Border>
|
||||||
|
|
||||||
|
<!-- Right panel -->
|
||||||
|
<Border Grid.Column="4"
|
||||||
|
Classes="dark_tr_bg white_border">
|
||||||
|
<Grid RowDefinitions="36 *">
|
||||||
|
<Border Classes="white_border" Margin="-1" Padding="4">
|
||||||
|
<DockPanel>
|
||||||
|
<TextBlock FontWeight="Bold"
|
||||||
|
DockPanel.Dock="Left">
|
||||||
|
Загрузки
|
||||||
|
</TextBlock>
|
||||||
|
<Button Click="ClearDownloadsPanel"
|
||||||
|
Classes="menu_button"
|
||||||
|
DockPanel.Dock="Right"
|
||||||
|
HorizontalAlignment="Right">
|
||||||
|
очистить
|
||||||
|
</Button>
|
||||||
|
</DockPanel>
|
||||||
|
</Border>
|
||||||
|
<ScrollViewer Grid.Row="1"
|
||||||
|
HorizontalScrollBarVisibility="Disabled"
|
||||||
|
VerticalScrollBarVisibility="Visible"
|
||||||
|
Background="Transparent"
|
||||||
|
Padding="1">
|
||||||
|
<StackPanel Name="DownloadsPanel"
|
||||||
|
VerticalAlignment="Top"/>
|
||||||
|
</ScrollViewer>
|
||||||
|
</Grid>
|
||||||
|
</Border>
|
||||||
|
</Grid>
|
||||||
|
<Border Grid.Row="1" Background="#954808B0">
|
||||||
|
<Grid>
|
||||||
|
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
|
||||||
|
<Button Classes="menu_button button_no_border" Click="ОткрытьПапкуЛаунчера">папка лаунчера</Button>
|
||||||
|
<Border Classes="menu_separator"/>
|
||||||
|
<Button Classes="menu_button button_no_border" Click="ОткрытьФайлЛогов">лог-файл</Button>
|
||||||
|
</StackPanel>
|
||||||
|
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
|
||||||
|
<TextBlock Name="LauncherVersionTextBox"/>
|
||||||
|
<Button Classes="menu_button button_no_border" Click="ОткрытьРепозиторий">исходный код</Button>
|
||||||
|
<gif:GifImage
|
||||||
|
Width="30" Height="30" Stretch="Uniform"
|
||||||
|
Source="avares://млаумчерб/капитал/лисик.gif"/>
|
||||||
|
</StackPanel>
|
||||||
|
</Grid>
|
||||||
|
</Border>
|
||||||
|
</Grid>
|
||||||
|
</Window>
|
||||||
368
Mlaumcherb.Client.Avalonia/зримое/MainWindow.axaml.cs
Normal file
@@ -0,0 +1,368 @@
|
|||||||
|
using System.Reflection;
|
||||||
|
using Avalonia;
|
||||||
|
using Avalonia.Controls;
|
||||||
|
using Avalonia.Data;
|
||||||
|
using Avalonia.Interactivity;
|
||||||
|
using Avalonia.Platform.Storage;
|
||||||
|
using Avalonia.Threading;
|
||||||
|
using Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
using Mlaumcherb.Client.Avalonia.холопы;
|
||||||
|
using MsBox.Avalonia;
|
||||||
|
using MsBox.Avalonia.Dto;
|
||||||
|
using MsBox.Avalonia.Models;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.зримое;
|
||||||
|
|
||||||
|
public partial class MainWindow : Window
|
||||||
|
{
|
||||||
|
public static readonly StyledProperty<string> PlayerNameProperty =
|
||||||
|
AvaloniaProperty.Register<MainWindow, string>(nameof(PlayerName),
|
||||||
|
defaultBindingMode: BindingMode.TwoWay);
|
||||||
|
public string PlayerName
|
||||||
|
{
|
||||||
|
get => GetValue(PlayerNameProperty);
|
||||||
|
set => SetValue(PlayerNameProperty, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static readonly StyledProperty<int> MemoryLimitProperty =
|
||||||
|
AvaloniaProperty.Register<MainWindow, int>(nameof(MemoryLimit),
|
||||||
|
defaultBindingMode: BindingMode.TwoWay, defaultValue: 2048);
|
||||||
|
public int MemoryLimit
|
||||||
|
{
|
||||||
|
get => GetValue(MemoryLimitProperty);
|
||||||
|
set => SetValue(MemoryLimitProperty, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static readonly StyledProperty<bool> UpdateGameFilesProperty =
|
||||||
|
AvaloniaProperty.Register<MainWindow, bool>(nameof(UpdateGameFiles),
|
||||||
|
defaultBindingMode: BindingMode.TwoWay, defaultValue: false);
|
||||||
|
public bool UpdateGameFiles
|
||||||
|
{
|
||||||
|
get => GetValue(UpdateGameFilesProperty);
|
||||||
|
set => SetValue(UpdateGameFilesProperty, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static readonly StyledProperty<bool> EnableJavaDownloadProperty =
|
||||||
|
AvaloniaProperty.Register<MainWindow, bool>(nameof(EnableJavaDownload),
|
||||||
|
defaultBindingMode: BindingMode.TwoWay, defaultValue: true);
|
||||||
|
public bool EnableJavaDownload
|
||||||
|
{
|
||||||
|
get => GetValue(EnableJavaDownloadProperty);
|
||||||
|
set => SetValue(EnableJavaDownloadProperty, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static readonly StyledProperty<bool> RedirectGameOutputProperty =
|
||||||
|
AvaloniaProperty.Register<MainWindow, bool>(nameof(RedirectGameOutput),
|
||||||
|
defaultBindingMode: BindingMode.TwoWay, defaultValue: false);
|
||||||
|
public bool RedirectGameOutput
|
||||||
|
{
|
||||||
|
get => GetValue(RedirectGameOutputProperty);
|
||||||
|
set => SetValue(RedirectGameOutputProperty, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public MainWindow()
|
||||||
|
{
|
||||||
|
InitializeComponent();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnLoaded(RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
LauncherApp.Logger.OnLogMessage += GuiLogMessage;
|
||||||
|
LauncherVersionTextBox.Text = $"v{Assembly.GetExecutingAssembly().GetName().Version}";
|
||||||
|
|
||||||
|
PlayerName = LauncherApp.Config.player_name;
|
||||||
|
MemoryLimit = LauncherApp.Config.max_memory;
|
||||||
|
EnableJavaDownload = LauncherApp.Config.download_java;
|
||||||
|
RedirectGameOutput = LauncherApp.Config.redirect_game_output;
|
||||||
|
|
||||||
|
foreach (var vc in LauncherApp.Config.version_catalogs)
|
||||||
|
{
|
||||||
|
RemoteVersionCatalogComboBox.Items.Add(vc);
|
||||||
|
}
|
||||||
|
RemoteVersionCatalogComboBox.SelectedIndex = 0;
|
||||||
|
|
||||||
|
UpdateInstalledVersionsCatalogView(LauncherApp.Config.last_launched_version);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
ErrorHelper.ShowMessageBox(nameof(MainWindow), ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnUnloaded(RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
SaveGuiPropertiesToConfig();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SaveGuiPropertiesToConfig()
|
||||||
|
{
|
||||||
|
LauncherApp.Config.player_name = PlayerName;
|
||||||
|
LauncherApp.Config.max_memory = MemoryLimit;
|
||||||
|
LauncherApp.Config.download_java = EnableJavaDownload;
|
||||||
|
LauncherApp.Config.redirect_game_output = RedirectGameOutput;
|
||||||
|
LauncherApp.Config.SaveToFile();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UpdateInstalledVersionsCatalogView(string? selectVersion)
|
||||||
|
{
|
||||||
|
LauncherApp.InstalledVersionCatalog.CheckInstalledVersions();
|
||||||
|
InstalledVersionCatalogComboBox.IsEnabled = false;
|
||||||
|
InstalledVersionCatalogComboBox.Items.Clear();
|
||||||
|
foreach (var p in LauncherApp.InstalledVersionCatalog.versions)
|
||||||
|
{
|
||||||
|
InstalledVersionCatalogComboBox.Items.Add(new InstalledGameVersionItemView(p.Value));
|
||||||
|
}
|
||||||
|
|
||||||
|
InstalledVersionCatalogComboBox.SelectedItem = null;
|
||||||
|
if(selectVersion is not null
|
||||||
|
&& LauncherApp.InstalledVersionCatalog.versions.TryGetValue(selectVersion, out var props))
|
||||||
|
{
|
||||||
|
foreach (InstalledGameVersionItemView? view in InstalledVersionCatalogComboBox.Items)
|
||||||
|
{
|
||||||
|
if (view?.Props.Id == props.Id)
|
||||||
|
{
|
||||||
|
InstalledVersionCatalogComboBox.SelectedItem = view;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
InstalledVersionCatalogComboBox.IsEnabled = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RescanInstalledVersionsButton_OnClick(object? sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var selectedVersionView = InstalledVersionCatalogComboBox.SelectedItem as InstalledGameVersionItemView;
|
||||||
|
UpdateInstalledVersionsCatalogView(selectedVersionView?.Props.Id);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
ErrorHelper.ShowMessageBox(nameof(MainWindow), ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void GuiLogMessage(LauncherLogger.LogMessage msg)
|
||||||
|
{
|
||||||
|
if (msg.severity == LogSeverity.Debug) return;
|
||||||
|
|
||||||
|
Dispatcher.UIThread.Invoke(() =>
|
||||||
|
{
|
||||||
|
double offsetFromBottom = LogScrollViewer.Extent.Height - LogScrollViewer.Offset.Y - LogScrollViewer.Viewport.Height;
|
||||||
|
bool is_scrolled_to_end = offsetFromBottom < 20.0; // scrolled less then one line up
|
||||||
|
LogPanel.Children.Add(new LogMessageView(msg));
|
||||||
|
if (is_scrolled_to_end) LogScrollViewer.ScrollToEnd();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async void Запуск(object? sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (InstalledVersionCatalogComboBox.SelectedItem is not InstalledGameVersionItemView selectedVersionView)
|
||||||
|
return;
|
||||||
|
|
||||||
|
Dispatcher.UIThread.Invoke(() => LaunchButton.IsEnabled = false);
|
||||||
|
LauncherApp.Config.last_launched_version = selectedVersionView.Props.Id;
|
||||||
|
SaveGuiPropertiesToConfig();
|
||||||
|
|
||||||
|
var v = await selectedVersionView.Props.LoadDescriptor(UpdateGameFiles);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await v.Download(UpdateGameFiles, nt =>
|
||||||
|
{
|
||||||
|
Dispatcher.UIThread.Invoke(() =>
|
||||||
|
{
|
||||||
|
DownloadsPanel.Children.Add(new NetworkTaskView(nt,
|
||||||
|
ntv => DownloadsPanel.Children.Remove(ntv)));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
ErrorHelper.ShowMessageBox(nameof(MainWindow), ex);
|
||||||
|
}
|
||||||
|
|
||||||
|
Dispatcher.UIThread.Invoke(() =>
|
||||||
|
{
|
||||||
|
UpdateGameFiles = false;
|
||||||
|
});
|
||||||
|
await v.Launch();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
ErrorHelper.ShowMessageBox(nameof(MainWindow), ex);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Dispatcher.UIThread.Invoke(() => LaunchButton.IsEnabled = true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ОткрытьПапкуЛаунчера(object? s, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
string workingDir = Directory.GetCurrent().ToString();
|
||||||
|
LauncherApp.Logger.LogDebug(nameof(MainWindow),
|
||||||
|
$"opening working directory: {workingDir}");
|
||||||
|
Launcher.LaunchDirectoryInfoAsync(new DirectoryInfo(workingDir))
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
ErrorHelper.ShowMessageBox(nameof(MainWindow), ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ОткрытьФайлЛогов(object? sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
string logFilePath = LauncherApp.Logger.LogFilePath.ToString();
|
||||||
|
LauncherApp.Logger.LogDebug(nameof(MainWindow),
|
||||||
|
$"opening log file: {logFilePath}");
|
||||||
|
Launcher.LaunchFileInfoAsync(new FileInfo(logFilePath))
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
ErrorHelper.ShowMessageBox(nameof(MainWindow), ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ОткрытьРепозиторий(object? sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var sourcesUri = new Uri(LauncherApp.Config.gitea.GetRepoUrl());
|
||||||
|
LauncherApp.Logger.LogDebug(nameof(MainWindow),
|
||||||
|
$"opening in web browser: {sourcesUri}");
|
||||||
|
Launcher.LaunchUriAsync(sourcesUri)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
ErrorHelper.ShowMessageBox(nameof(MainWindow), ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ClearLogPanel(object? sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
LogPanel.Children.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private void ClearDownloadsPanel(object? sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
foreach (var control in DownloadsPanel.Children)
|
||||||
|
{
|
||||||
|
var nt = (NetworkTaskView)control;
|
||||||
|
nt.Task.Cancel();
|
||||||
|
}
|
||||||
|
DownloadsPanel.Children.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async void SearchVersionsButton_OnClick(object? sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if(RemoteVersionCatalogComboBox.SelectedItem is not GameVersionCatalogProps catalogProps)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var catalog = await catalogProps.GetVersionCatalogAsync();
|
||||||
|
var searchParams = new VersionSearchParams
|
||||||
|
{
|
||||||
|
ReleaseTypeAllowed = ReleaseVersionTypeCheckBox.IsChecked ?? false,
|
||||||
|
SnapshotTypeAllowed = SnapshotVersionTypeCheckBox.IsChecked ?? false,
|
||||||
|
OldTypeAllowed = OldVersionTypeCheckBox.IsChecked ?? false,
|
||||||
|
OtherTypeAllowed = OtherVersionTypeAlphaCheckBox.IsChecked ?? false
|
||||||
|
};
|
||||||
|
var versions = catalog.GetDownloadableVersions(searchParams);
|
||||||
|
|
||||||
|
Dispatcher.UIThread.Invoke(() =>
|
||||||
|
{
|
||||||
|
RemoteVersionCatalogItemsComboBox.IsEnabled = false;
|
||||||
|
RemoteVersionCatalogItemsComboBox.Items.Clear();
|
||||||
|
foreach (var p in versions)
|
||||||
|
{
|
||||||
|
RemoteVersionCatalogItemsComboBox.Items.Add(new RemoteGameVersionItemView(p));
|
||||||
|
}
|
||||||
|
RemoteVersionCatalogItemsComboBox.IsEnabled = true;
|
||||||
|
AddVersionButton.IsEnabled = versions.Count > 0;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
ErrorHelper.ShowMessageBox(nameof(MainWindow), ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void AddVersionButton_OnClick(object? sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if(RemoteVersionCatalogComboBox.SelectedItem is not GameVersionCatalogProps catalogProps)
|
||||||
|
return;
|
||||||
|
|
||||||
|
if(RemoteVersionCatalogItemsComboBox.SelectedItem is not RemoteGameVersionItemView sel)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var installedProps = new InstalledGameVersionProps(sel.Props.id, catalogProps, sel.Props);
|
||||||
|
if (!LauncherApp.InstalledVersionCatalog.versions.TryAdd(sel.Props.id, installedProps))
|
||||||
|
throw new Exception("Версия уже была добавлена");
|
||||||
|
LauncherApp.InstalledVersionCatalog.Save();
|
||||||
|
|
||||||
|
var propsView = new InstalledGameVersionItemView(installedProps);
|
||||||
|
InstalledVersionCatalogComboBox.Items.Insert(0, propsView);
|
||||||
|
InstalledVersionCatalogComboBox.SelectedItem = propsView;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
ErrorHelper.ShowMessageBox(nameof(MainWindow), ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async void DeleteVersionButton_OnClick(object? sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if(InstalledVersionCatalogComboBox.SelectedItem is not InstalledGameVersionItemView sel)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var box = MessageBoxManager.GetMessageBoxCustom(new MessageBoxCustomParams
|
||||||
|
{
|
||||||
|
ButtonDefinitions = new List<ButtonDefinition> { new() { Name = "Да" }, new() { Name = "Нет" } },
|
||||||
|
ContentTitle = $"Удаление версии {sel.Props.Id}",
|
||||||
|
ContentMessage = $"Вы уверены, что хотите удалить версию {sel.Props.Id}? Все файлы, включая сохранения, будут удалены!",
|
||||||
|
Icon = MsBox.Avalonia.Enums.Icon.Question,
|
||||||
|
WindowStartupLocation = WindowStartupLocation.CenterOwner,
|
||||||
|
SizeToContent = SizeToContent.WidthAndHeight,
|
||||||
|
ShowInCenter = true,
|
||||||
|
Topmost = true
|
||||||
|
}
|
||||||
|
);
|
||||||
|
var result = await box.ShowAsync().ConfigureAwait(false);
|
||||||
|
if (result != "Да")
|
||||||
|
return;
|
||||||
|
|
||||||
|
sel.Props.Delete();
|
||||||
|
Dispatcher.UIThread.Invoke(() =>
|
||||||
|
{
|
||||||
|
InstalledVersionCatalogComboBox.Items.Remove(sel);
|
||||||
|
LauncherApp.InstalledVersionCatalog.versions.Remove(sel.Props.Id);
|
||||||
|
LauncherApp.InstalledVersionCatalog.Save();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
ErrorHelper.ShowMessageBox(nameof(MainWindow), ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Before Width: | Height: | Size: 3.5 KiB After Width: | Height: | Size: 3.5 KiB |
|
Before Width: | Height: | Size: 39 KiB After Width: | Height: | Size: 39 KiB |
|
Before Width: | Height: | Size: 1.1 MiB After Width: | Height: | Size: 1.1 MiB |
@@ -0,0 +1,54 @@
|
|||||||
|
namespace Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
|
||||||
|
public record VersionSearchParams
|
||||||
|
{
|
||||||
|
public bool ReleaseTypeAllowed;
|
||||||
|
public bool SnapshotTypeAllowed;
|
||||||
|
public bool OldTypeAllowed;
|
||||||
|
public bool OtherTypeAllowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public class GameVersionCatalog
|
||||||
|
{
|
||||||
|
[JsonRequired] public List<RemoteVersionDescriptorProps> versions { get; set; } = new();
|
||||||
|
|
||||||
|
/// <returns>empty list if couldn't find any remote versions</returns>
|
||||||
|
public List<RemoteVersionDescriptorProps> GetDownloadableVersions(VersionSearchParams p)
|
||||||
|
{
|
||||||
|
var _versionPropsList = new List<RemoteVersionDescriptorProps>();
|
||||||
|
foreach (var r in versions)
|
||||||
|
{
|
||||||
|
bool match = r.type switch
|
||||||
|
{
|
||||||
|
"release" => p.ReleaseTypeAllowed,
|
||||||
|
"snapshot" => p.SnapshotTypeAllowed,
|
||||||
|
"old_alpha" or "old_beta" => p.OldTypeAllowed,
|
||||||
|
_ => p.OtherTypeAllowed
|
||||||
|
};
|
||||||
|
if(match)
|
||||||
|
_versionPropsList.Add(r);
|
||||||
|
}
|
||||||
|
return _versionPropsList;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class AssetProperties
|
||||||
|
{
|
||||||
|
[JsonRequired] public string hash { get; set; } = "";
|
||||||
|
[JsonRequired] public int size { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class AssetIndex
|
||||||
|
{
|
||||||
|
[JsonRequired] public Dictionary<string, AssetProperties> objects { get; set; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
public class RemoteVersionDescriptorProps
|
||||||
|
{
|
||||||
|
[JsonRequired] public string id { get; set; } = "";
|
||||||
|
[JsonRequired] public string url { get; set; } = "";
|
||||||
|
[JsonRequired] public string type { get; set; } = "";
|
||||||
|
public string sha1 { get; set; } = "";
|
||||||
|
public DateTime time { get; set; }
|
||||||
|
public DateTime releaseTime { get; set; }
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
using System.Linq;
|
using System.Linq;
|
||||||
// ReSharper disable CollectionNeverUpdated.Global
|
// ReSharper disable CollectionNeverUpdated.Global
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент.классы;
|
namespace Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
|
||||||
public class GameVersionDescriptor
|
public class GameVersionDescriptor
|
||||||
{
|
{
|
||||||
@@ -10,17 +10,21 @@ public class GameVersionDescriptor
|
|||||||
[JsonRequired] public DateTime releaseTime { get; set; }
|
[JsonRequired] public DateTime releaseTime { get; set; }
|
||||||
[JsonRequired] public string type { get; set; } = "";
|
[JsonRequired] public string type { get; set; } = "";
|
||||||
[JsonRequired] public string mainClass { get; set; } = "";
|
[JsonRequired] public string mainClass { get; set; } = "";
|
||||||
[JsonRequired] public Downloads downloads { get; set; } = null!;
|
[JsonRequired] public List<Library> libraries { get; set; } = new();
|
||||||
[JsonRequired] public JavaVersion javaVersion { get; set; } = null!;
|
|
||||||
[JsonRequired] public List<Library> libraries { get; set; } = null!;
|
|
||||||
[JsonRequired] public AssetIndexProperties assetIndex { get; set; } = null!;
|
[JsonRequired] public AssetIndexProperties assetIndex { get; set; } = null!;
|
||||||
[JsonRequired] public string assets { get; set; } = "";
|
[JsonRequired] public string assets { get; set; } = "";
|
||||||
|
public Downloads? downloads { get; set; } = null;
|
||||||
|
public JavaVersion javaVersion { get; set; } = new() { component = "jre-legacy", majorVersion = 8 };
|
||||||
public string? minecraftArguments { get; set; }
|
public string? minecraftArguments { get; set; }
|
||||||
public ArgumentsNew? arguments { get; set; }
|
public ArgumentsNew? arguments { get; set; }
|
||||||
|
|
||||||
|
// my additions
|
||||||
|
public MyModpackRemoteProps? modpack { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
public class Artifact
|
public class Artifact
|
||||||
{
|
{
|
||||||
|
public string? path = null;
|
||||||
[JsonRequired] public string url { get; set; } = "";
|
[JsonRequired] public string url { get; set; } = "";
|
||||||
[JsonRequired] public string sha1 { get; set; } = "";
|
[JsonRequired] public string sha1 { get; set; } = "";
|
||||||
[JsonRequired] public int size { get; set; }
|
[JsonRequired] public int size { get; set; }
|
||||||
@@ -63,7 +67,7 @@ public class Library
|
|||||||
public List<Rule>? rules { get; set; }
|
public List<Rule>? rules { get; set; }
|
||||||
public Natives? natives { get; set; }
|
public Natives? natives { get; set; }
|
||||||
public Extract? extract { get; set; }
|
public Extract? extract { get; set; }
|
||||||
[JsonRequired] public LibraryDownloads downloads { get; set; } = null!;
|
public LibraryDownloads? downloads { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
public class AssetIndexProperties
|
public class AssetIndexProperties
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using Mlaumcherb.Client.Avalonia.холопы;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
|
||||||
|
public class JavaVersionCatalog
|
||||||
|
{
|
||||||
|
[JsonProperty("linux-i386")]
|
||||||
|
public Dictionary<string, JavaVersionProps[]>? linux_x86 { get; set; }
|
||||||
|
[JsonProperty("linux")]
|
||||||
|
public Dictionary<string, JavaVersionProps[]>? linux_x64 { get; set; }
|
||||||
|
[JsonProperty("mac-os")]
|
||||||
|
public Dictionary<string, JavaVersionProps[]>? osx_x64 { get; set; }
|
||||||
|
[JsonProperty("mac-os-arm64")]
|
||||||
|
public Dictionary<string, JavaVersionProps[]>? osx_arm64 { get; set; }
|
||||||
|
[JsonProperty("windows-arm64")]
|
||||||
|
public Dictionary<string, JavaVersionProps[]>? windows_arm64 { get; set; }
|
||||||
|
[JsonProperty("windows-x64")]
|
||||||
|
public Dictionary<string, JavaVersionProps[]>? windows_x64 { get; set; }
|
||||||
|
[JsonProperty("windows-x86")]
|
||||||
|
public Dictionary<string, JavaVersionProps[]>? windows_x86 { get; set; }
|
||||||
|
|
||||||
|
public JavaVersionProps GetVersionProps(JavaVersion version)
|
||||||
|
{
|
||||||
|
var arch = RuntimeInformation.OSArchitecture;
|
||||||
|
Dictionary<string, JavaVersionProps[]>? propsDict = null;
|
||||||
|
switch (arch)
|
||||||
|
{
|
||||||
|
case Architecture.X86:
|
||||||
|
if (OperatingSystem.IsWindows())
|
||||||
|
propsDict = windows_x86;
|
||||||
|
else if (OperatingSystem.IsLinux())
|
||||||
|
propsDict = linux_x86;
|
||||||
|
break;
|
||||||
|
case Architecture.X64:
|
||||||
|
if (OperatingSystem.IsWindows())
|
||||||
|
propsDict = windows_x64;
|
||||||
|
else if (OperatingSystem.IsLinux())
|
||||||
|
propsDict = linux_x64;
|
||||||
|
else if (OperatingSystem.IsMacOS())
|
||||||
|
propsDict = osx_x64;
|
||||||
|
break;
|
||||||
|
case Architecture.Arm64:
|
||||||
|
if (OperatingSystem.IsWindows())
|
||||||
|
propsDict = windows_arm64;
|
||||||
|
else if (OperatingSystem.IsMacOS())
|
||||||
|
propsDict = osx_arm64;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (propsDict != null && propsDict.TryGetValue(version.component, out var props_array))
|
||||||
|
{
|
||||||
|
if (props_array.Length != 0)
|
||||||
|
return props_array[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new PlatformNotSupportedException($"Can't download java {version.majorVersion} for your operating system. " +
|
||||||
|
$"Download it manually to directory {PathHelper.GetJavaRuntimeDir(version.component)}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class JavaVersionProps
|
||||||
|
{
|
||||||
|
/// url of JavaDistributiveManifest
|
||||||
|
[JsonRequired] public Artifact manifest { get; set; } = null!;
|
||||||
|
}
|
||||||
|
|
||||||
|
public class JavaDistributiveManifest
|
||||||
|
{
|
||||||
|
[JsonRequired] public Dictionary<string, JavaDistributiveElementProps> files { get; set; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
public class JavaDistributiveElementProps
|
||||||
|
{
|
||||||
|
/// "directory" / "file"
|
||||||
|
[JsonRequired] public string type { get; set; } = "";
|
||||||
|
public bool? executable { get; set; }
|
||||||
|
public JavaCompressedArtifact? downloads { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class JavaCompressedArtifact
|
||||||
|
{
|
||||||
|
public Artifact? lzma { get; set; }
|
||||||
|
[JsonRequired] public Artifact raw { get; set; } = null!;
|
||||||
|
}
|
||||||
40
Mlaumcherb.Client.Avalonia/классы/Буржуазия/Rules.cs
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
using Mlaumcherb.Client.Avalonia.холопы;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
|
||||||
|
public static class Rules
|
||||||
|
{
|
||||||
|
public static bool Check(ICollection<Rule>? rules, ICollection<string> features)
|
||||||
|
{
|
||||||
|
if(rules is null || rules.Count == 0)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
bool allowed = false;
|
||||||
|
foreach (var r in rules)
|
||||||
|
{
|
||||||
|
if (r.os != null && !PlatformHelper.CheckOs(r.os))
|
||||||
|
continue;
|
||||||
|
|
||||||
|
if (r.features == null)
|
||||||
|
allowed = r.action == "allow";
|
||||||
|
else
|
||||||
|
{
|
||||||
|
foreach (var feature in features)
|
||||||
|
{
|
||||||
|
if (r.features.TryGetValue(feature, out bool is_enabled))
|
||||||
|
{
|
||||||
|
if (is_enabled)
|
||||||
|
{
|
||||||
|
allowed = r.action == "allow";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if(allowed)
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return allowed;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
namespace Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
|
||||||
|
public class ArgumentsWithPlaceholders
|
||||||
|
{
|
||||||
|
protected List<string> _raw_args = new();
|
||||||
|
|
||||||
|
public IEnumerable<string> FillPlaceholders(Dictionary<string, string> values)
|
||||||
|
{
|
||||||
|
foreach (var _s in _raw_args)
|
||||||
|
{
|
||||||
|
string arg = _s;
|
||||||
|
int begin = arg.IndexOf("${", StringComparison.Ordinal);
|
||||||
|
while(begin != -1)
|
||||||
|
{
|
||||||
|
int keyBegin = begin + 2;
|
||||||
|
int end = arg.IndexOf('}', keyBegin);
|
||||||
|
if (end != -1)
|
||||||
|
{
|
||||||
|
var key = arg.Substring(keyBegin, end - keyBegin);
|
||||||
|
if (!values.TryGetValue(key, out var value))
|
||||||
|
throw new Exception($"can't find value for placeholder '{key}'");
|
||||||
|
arg = arg.Replace("${"+ key + "}", value);
|
||||||
|
}
|
||||||
|
if(end + 1 < arg.Length)
|
||||||
|
begin = arg.IndexOf("${", end + 1, StringComparison.Ordinal);
|
||||||
|
else break;
|
||||||
|
}
|
||||||
|
yield return arg;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
using DTLib.Extensions;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
|
||||||
|
public class GameArguments : ArgumentsWithPlaceholders
|
||||||
|
{
|
||||||
|
private static readonly string[] _initial_arguments =
|
||||||
|
[
|
||||||
|
"--width", "${resolution_width}",
|
||||||
|
"--height", "${resolution_height}",
|
||||||
|
];
|
||||||
|
|
||||||
|
private static readonly string[] _enabled_features =
|
||||||
|
[
|
||||||
|
];
|
||||||
|
|
||||||
|
public GameArguments(GameVersionDescriptor d)
|
||||||
|
{
|
||||||
|
_raw_args.AddRange(_initial_arguments);
|
||||||
|
|
||||||
|
if (d.minecraftArguments is not null)
|
||||||
|
{
|
||||||
|
_raw_args.AddRange(d.minecraftArguments.SplitToList(' ', quot: '"'));
|
||||||
|
}
|
||||||
|
else if (d.arguments is not null)
|
||||||
|
{
|
||||||
|
foreach (var av in d.arguments.game)
|
||||||
|
{
|
||||||
|
if(Rules.Check(av.rules, _enabled_features))
|
||||||
|
{
|
||||||
|
foreach (var arg in av.value)
|
||||||
|
{
|
||||||
|
// if(!_raw_args.Contains(arg))
|
||||||
|
_raw_args.Add(arg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else throw new Exception("no game arguments specified in descriptor");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
using Mlaumcherb.Client.Avalonia.сеть;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
|
||||||
|
|
||||||
|
public class GameVersionCatalogProps
|
||||||
|
{
|
||||||
|
[JsonRequired] public required string name { get; init; }
|
||||||
|
[JsonRequired] public required string url { get; init; }
|
||||||
|
|
||||||
|
public override string ToString() => name;
|
||||||
|
|
||||||
|
public async Task<GameVersionCatalog> GetVersionCatalogAsync()
|
||||||
|
{
|
||||||
|
return await NetworkHelper.DownloadStringAndDeserialize<GameVersionCatalog>(url);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
using Mlaumcherb.Client.Avalonia.зримое;
|
||||||
|
using Mlaumcherb.Client.Avalonia.сеть;
|
||||||
|
using Mlaumcherb.Client.Avalonia.холопы;
|
||||||
|
using Newtonsoft.Json.Linq;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
|
||||||
|
public class InstalledGameVersionProps : IComparable<InstalledGameVersionProps>, IEquatable<InstalledGameVersionProps>
|
||||||
|
{
|
||||||
|
[JsonRequired] public string Id { get; }
|
||||||
|
public GameVersionCatalogProps? CatalogProps { get; set; }
|
||||||
|
|
||||||
|
public RemoteVersionDescriptorProps? DescriptorProps { get; set; }
|
||||||
|
|
||||||
|
|
||||||
|
private bool _isInstalled;
|
||||||
|
[JsonIgnore]
|
||||||
|
public bool IsInstalled
|
||||||
|
{
|
||||||
|
get => _isInstalled;
|
||||||
|
set
|
||||||
|
{
|
||||||
|
_isInstalled = value;
|
||||||
|
StatusChanged?.Invoke(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[JsonIgnore] public IOPath DescriptorPath { get; }
|
||||||
|
|
||||||
|
public event Action<bool>? StatusChanged;
|
||||||
|
|
||||||
|
public InstalledGameVersionProps(string id, GameVersionCatalogProps? catalogProps, RemoteVersionDescriptorProps? descriptorProps)
|
||||||
|
{
|
||||||
|
this.Id = id;
|
||||||
|
this.CatalogProps = catalogProps;
|
||||||
|
this.DescriptorProps = descriptorProps;
|
||||||
|
DescriptorPath = PathHelper.GetVersionDescriptorPath(id);
|
||||||
|
IsInstalled = File.Exists(PathHelper.GetVersionJarFilePath(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<GameVersion> LoadDescriptor(bool checkForUpdates)
|
||||||
|
{
|
||||||
|
// check if DescriptorProps had been changed on on remote version catalog server
|
||||||
|
if (checkForUpdates && CatalogProps is not null && DescriptorProps is not null)
|
||||||
|
{
|
||||||
|
var remoteCatalog = await NetworkHelper.DownloadStringAndDeserialize<GameVersionCatalog>(CatalogProps.url);
|
||||||
|
|
||||||
|
DescriptorProps = remoteCatalog.versions.Find(remoteProps => remoteProps.id == Id);
|
||||||
|
if(DescriptorProps is null)
|
||||||
|
LauncherApp.Logger.LogWarn(nameof(InstalledGameVersionProps),
|
||||||
|
$"Game version '{Id}' was deleted from remote catalog '{CatalogProps.name}'."
|
||||||
|
+ "It is kept locally, but can't be updated anymore.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Descriptor is downloaded here
|
||||||
|
if (!HashHelper.CheckFileSHA1(DescriptorPath, DescriptorProps?.sha1, checkForUpdates))
|
||||||
|
{
|
||||||
|
if (DescriptorProps is null)
|
||||||
|
throw new NullReferenceException(
|
||||||
|
$"can't download game version descriptor '{Id}', because RemoteDescriptor is null");
|
||||||
|
// download descriptor
|
||||||
|
await NetworkHelper.DownloadFile(DescriptorProps.url, DescriptorPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
string descriptorText = File.ReadAllText(DescriptorPath);
|
||||||
|
JObject descriptorRaw = JObject.Parse(descriptorText);
|
||||||
|
|
||||||
|
// Descriptors can inherit from other descriptors.
|
||||||
|
// For example, timerix-anarx-2 inherits from 1.12.2-forge-14.23.5.2860, which inherits from 1.12.2
|
||||||
|
while (descriptorRaw.TryGetValue("inheritsFrom", out var v))
|
||||||
|
{
|
||||||
|
string parentDescriptorId = v.Value<string>()
|
||||||
|
?? throw new Exception("inheritsFrom is null");
|
||||||
|
LauncherApp.Logger.LogInfo(Id, $"merging descriptor '{parentDescriptorId}' with '{Id}'");
|
||||||
|
|
||||||
|
IOPath parentDescriptorPath = PathHelper.GetVersionDescriptorPath(parentDescriptorId);
|
||||||
|
if (!File.Exists(parentDescriptorPath))
|
||||||
|
throw new Exception($"Версия '{Id} требует установить версию '{parentDescriptorId}'");
|
||||||
|
JObject parentDescriptorRaw = JObject.Parse(File.ReadAllText(parentDescriptorPath));
|
||||||
|
|
||||||
|
// Remove `inheritsFrom: parentDescriptor.Id` to prevent overriding of `parentDescriptor.inheritsFrom`
|
||||||
|
descriptorRaw.Remove("inheritsFrom");
|
||||||
|
// Merge child descriptor into its parent.
|
||||||
|
// Child descriptor values override values of parent.
|
||||||
|
// Array values are merged together.
|
||||||
|
parentDescriptorRaw.Merge(descriptorRaw,
|
||||||
|
new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Concat });
|
||||||
|
descriptorRaw = parentDescriptorRaw;
|
||||||
|
}
|
||||||
|
|
||||||
|
var descriptor = descriptorRaw.ToObject<GameVersionDescriptor>()
|
||||||
|
?? throw new Exception($"can't parse descriptor file '{DescriptorPath}'");
|
||||||
|
|
||||||
|
return new GameVersion(this, descriptor);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Delete()
|
||||||
|
{
|
||||||
|
if(!IsInstalled)
|
||||||
|
return;
|
||||||
|
|
||||||
|
LauncherApp.Logger.LogInfo(Id, "Deleting files...");
|
||||||
|
var verdir = PathHelper.GetVersionDir(Id);
|
||||||
|
if(Directory.Exists(verdir))
|
||||||
|
Directory.Delete(verdir);
|
||||||
|
LauncherApp.Logger.LogInfo(Id, "Files deleted");
|
||||||
|
IsInstalled = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override string ToString() => Id;
|
||||||
|
|
||||||
|
public override int GetHashCode() => Id.GetHashCode();
|
||||||
|
|
||||||
|
public int CompareTo(InstalledGameVersionProps? other)
|
||||||
|
{
|
||||||
|
if (ReferenceEquals(this, other))
|
||||||
|
return 0;
|
||||||
|
if (other is null)
|
||||||
|
return 1;
|
||||||
|
|
||||||
|
return String.Compare(Id, other.Id, StringComparison.InvariantCulture);
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Equals(InstalledGameVersionProps? other)
|
||||||
|
{
|
||||||
|
if (other is null) return false;
|
||||||
|
if (ReferenceEquals(this, other)) return true;
|
||||||
|
return Id == other.Id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool Equals(object? obj)
|
||||||
|
{
|
||||||
|
if (obj is InstalledGameVersionProps other) return Equals(other);
|
||||||
|
if (ReferenceEquals(this, obj)) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
using System.Linq;
|
||||||
|
using Mlaumcherb.Client.Avalonia.зримое;
|
||||||
|
using Mlaumcherb.Client.Avalonia.холопы;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
|
||||||
|
public class InstalledVersionCatalog
|
||||||
|
{
|
||||||
|
/// version_id, props
|
||||||
|
[JsonRequired] public Dictionary<string, InstalledGameVersionProps> versions { get; set; } = new();
|
||||||
|
|
||||||
|
private IComparer<InstalledGameVersionProps> reverseComparer = new ReverseComparer<InstalledGameVersionProps>();
|
||||||
|
|
||||||
|
public static InstalledVersionCatalog Load()
|
||||||
|
{
|
||||||
|
InstalledVersionCatalog catalog;
|
||||||
|
var installedCatalogPath = PathHelper.GetInstalledVersionCatalogPath();
|
||||||
|
if (!File.Exists(installedCatalogPath))
|
||||||
|
{
|
||||||
|
LauncherApp.Logger.LogDebug(nameof(InstalledVersionCatalog), "creating new catalog");
|
||||||
|
catalog = new InstalledVersionCatalog();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
LauncherApp.Logger.LogDebug(nameof(InstalledVersionCatalog), "loading catalog from file");
|
||||||
|
catalog = JsonConvert.DeserializeObject<InstalledVersionCatalog>(
|
||||||
|
File.ReadAllText(installedCatalogPath))
|
||||||
|
?? throw new NullReferenceException($"can't deserialize {installedCatalogPath}");
|
||||||
|
}
|
||||||
|
|
||||||
|
catalog.CheckInstalledVersions();
|
||||||
|
return catalog;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Save()
|
||||||
|
{
|
||||||
|
var installedCatalogPath = PathHelper.GetInstalledVersionCatalogPath();
|
||||||
|
LauncherApp.Logger.LogDebug(nameof(InstalledVersionCatalog), "saving catalog to file");
|
||||||
|
var text = JsonConvert.SerializeObject(this, Formatting.Indented);
|
||||||
|
File.WriteAllText(installedCatalogPath, text);
|
||||||
|
LauncherApp.Logger.LogDebug(nameof(InstalledVersionCatalog), "catalog has been saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Check if any versions were installed or deleted manually.
|
||||||
|
/// Calls <see cref="Save"/>
|
||||||
|
/// </summary>
|
||||||
|
public void CheckInstalledVersions()
|
||||||
|
{
|
||||||
|
var versionsUpdated = new List<InstalledGameVersionProps>();
|
||||||
|
Directory.Create(PathHelper.GetVersionsDir());
|
||||||
|
foreach (var subdir in Directory.GetDirectories(PathHelper.GetVersionsDir()))
|
||||||
|
{
|
||||||
|
string id = subdir.LastName().ToString();
|
||||||
|
if (!File.Exists(PathHelper.GetVersionDescriptorPath(id)))
|
||||||
|
{
|
||||||
|
LauncherApp.Logger.LogWarn(nameof(CheckInstalledVersions),
|
||||||
|
$"Can't find version descriptor file in directory '{subdir}'. " +
|
||||||
|
$"Rename it as directory name.");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (versions.TryGetValue(id, out var foundProps))
|
||||||
|
versionsUpdated.Add(foundProps);
|
||||||
|
else versionsUpdated.Add(new InstalledGameVersionProps(id, null, null));
|
||||||
|
}
|
||||||
|
|
||||||
|
// reverse sort
|
||||||
|
versionsUpdated.Sort(reverseComparer);
|
||||||
|
// create dictionary from list
|
||||||
|
versions = new Dictionary<string, InstalledGameVersionProps>(
|
||||||
|
versionsUpdated.Select(props =>
|
||||||
|
new KeyValuePair<string, InstalledGameVersionProps>(props.Id, props)
|
||||||
|
));
|
||||||
|
|
||||||
|
Save();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
namespace Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
|
||||||
|
public class JavaArguments : ArgumentsWithPlaceholders
|
||||||
|
{
|
||||||
|
private static readonly string[] _initial_arguments =
|
||||||
|
[
|
||||||
|
"-XX:+UnlockExperimentalVMOptions",
|
||||||
|
"-XX:+UseG1GC",
|
||||||
|
"-XX:G1NewSizePercent=20",
|
||||||
|
"-XX:G1ReservePercent=20",
|
||||||
|
"-XX:MaxGCPauseMillis=50",
|
||||||
|
"-XX:G1HeapRegionSize=32M",
|
||||||
|
"-XX:+DisableExplicitGC",
|
||||||
|
"-XX:+AlwaysPreTouch",
|
||||||
|
"-XX:+ParallelRefProcEnabled",
|
||||||
|
"-Xms${xms}M",
|
||||||
|
"-Xmx${xmx}M",
|
||||||
|
"-Dfile.encoding=UTF-8",
|
||||||
|
"-Dlog4j.configurationFile=${path}",
|
||||||
|
"-Djava.library.path=${natives_directory}",
|
||||||
|
"-Dminecraft.client.jar=${client_jar}",
|
||||||
|
"-Dminecraft.launcher.brand=${launcher_name}",
|
||||||
|
"-Dminecraft.launcher.version=${launcher_version}",
|
||||||
|
];
|
||||||
|
|
||||||
|
private static readonly string[] _enabled_features =
|
||||||
|
[
|
||||||
|
];
|
||||||
|
|
||||||
|
public JavaArguments(GameVersionDescriptor d)
|
||||||
|
{
|
||||||
|
_raw_args.AddRange(_initial_arguments);
|
||||||
|
if (d.arguments is not null)
|
||||||
|
{
|
||||||
|
foreach (var av in d.arguments.jvm)
|
||||||
|
{
|
||||||
|
if (Rules.Check(av.rules, _enabled_features))
|
||||||
|
{
|
||||||
|
foreach (var arg in av.value)
|
||||||
|
{
|
||||||
|
// if(!_raw_args.Contains(arg))
|
||||||
|
_raw_args.Add(arg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!_raw_args.Contains("-cp"))
|
||||||
|
{
|
||||||
|
_raw_args.Add("-cp");
|
||||||
|
_raw_args.Add("${classpath}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
107
Mlaumcherb.Client.Avalonia/классы/Пролетариат/Libraries.cs
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
using DTLib.Extensions;
|
||||||
|
using Mlaumcherb.Client.Avalonia.холопы;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
|
||||||
|
public class Libraries
|
||||||
|
{
|
||||||
|
private static readonly string[] enabled_features = [];
|
||||||
|
|
||||||
|
public record JarLib(string name, IOPath jarFilePath, Artifact? artifact);
|
||||||
|
public record NativeLib(string name, IOPath jarFilePath, Artifact? artifact, Extract? extractionOptions)
|
||||||
|
: JarLib(name, jarFilePath, artifact);
|
||||||
|
|
||||||
|
public IReadOnlyCollection<JarLib> Libs { get; }
|
||||||
|
|
||||||
|
public static IOPath GetPathFromMavenName(string mavenName, string ext = "jar")
|
||||||
|
{
|
||||||
|
int sep_0 = mavenName.IndexOf(':');
|
||||||
|
if (sep_0 == -1)
|
||||||
|
throw new ArgumentException($"Invalid maven name: {mavenName}");
|
||||||
|
int sep_1 = mavenName.IndexOf(':', sep_0 + 1);
|
||||||
|
if (sep_1 == -1)
|
||||||
|
throw new ArgumentException($"Invalid maven name: {mavenName}");
|
||||||
|
var package = mavenName.Substring(0, sep_0).Replace('.', '/');
|
||||||
|
var artifact = mavenName.Substring(sep_0 + 1, sep_1 - sep_0 - 1);
|
||||||
|
var version = mavenName.Substring(sep_1 + 1);
|
||||||
|
string file_name = $"{artifact}-{version}.{ext}";
|
||||||
|
return Path.Concat(PathHelper.GetLibrariesDir(), package, artifact, version, file_name);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IOPath GetPathFromArtifact(Artifact artifact)
|
||||||
|
{
|
||||||
|
string relativePath;
|
||||||
|
if (!string.IsNullOrEmpty(artifact.path))
|
||||||
|
relativePath = artifact.path;
|
||||||
|
else if (!string.IsNullOrEmpty(artifact.url))
|
||||||
|
relativePath = artifact.url.AsSpan().After("://").After('/').ToString();
|
||||||
|
else throw new ArgumentException("Artifact must have a path or url");
|
||||||
|
|
||||||
|
return Path.Concat(PathHelper.GetLibrariesDir(), relativePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Libraries(GameVersionDescriptor descriptor)
|
||||||
|
{
|
||||||
|
List<JarLib> libs = new();
|
||||||
|
HashSet<string> libHashes = new();
|
||||||
|
|
||||||
|
foreach (var l in descriptor.libraries)
|
||||||
|
{
|
||||||
|
if (l.rules != null && !Rules.Check(l.rules, enabled_features))
|
||||||
|
continue;
|
||||||
|
|
||||||
|
if (l.natives != null)
|
||||||
|
{
|
||||||
|
string? nativesKey;
|
||||||
|
if (OperatingSystem.IsWindows())
|
||||||
|
nativesKey = l.natives.windows;
|
||||||
|
else if (OperatingSystem.IsLinux())
|
||||||
|
nativesKey = l.natives.linux;
|
||||||
|
else if (OperatingSystem.IsMacOS())
|
||||||
|
nativesKey = l.natives.osx;
|
||||||
|
else throw new PlatformNotSupportedException();
|
||||||
|
if(nativesKey is null)
|
||||||
|
throw new Exception($"nativesKey for '{l.name}' is null");
|
||||||
|
|
||||||
|
// example: "natives-windows-${arch}"
|
||||||
|
if (nativesKey.Contains('$'))
|
||||||
|
{
|
||||||
|
var span = nativesKey.AsSpan();
|
||||||
|
nativesKey = span.After("${").Before('}') switch
|
||||||
|
{
|
||||||
|
"arch" => span.Before("${").ToString() + PlatformHelper.GetArchOld(),
|
||||||
|
_ => throw new Exception($"unknown placeholder in {nativesKey}")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
Artifact artifact = null!;
|
||||||
|
if(l.downloads?.classifiers != null && !l.downloads.classifiers.TryGetValue(nativesKey, out artifact!))
|
||||||
|
throw new Exception($"can't find artifact for '{l.name}' with nativesKey '{nativesKey}'");
|
||||||
|
|
||||||
|
// skipping duplicates (WHO THE HELL CREATES THIS DISCRIPTORS AAAAAAAAA)
|
||||||
|
if(!libHashes.Add(artifact.sha1))
|
||||||
|
continue;
|
||||||
|
|
||||||
|
libs.Add(new NativeLib(l.name, GetPathFromArtifact(artifact), artifact, l.extract));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Artifact? artifact = l.downloads?.artifact;
|
||||||
|
if (artifact is null)
|
||||||
|
{
|
||||||
|
libs.Add(new JarLib(l.name, GetPathFromMavenName(l.name), artifact));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// skipping duplicates
|
||||||
|
if (!libHashes.Add(artifact.sha1))
|
||||||
|
continue;
|
||||||
|
|
||||||
|
libs.Add(new JarLib(l.name, GetPathFromArtifact(artifact), artifact));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Libs = libs;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
|
||||||
|
public class MyModpackRemoteProps
|
||||||
|
{
|
||||||
|
[JsonRequired] public int format_version { get; set; }
|
||||||
|
[JsonRequired] public Artifact artifact { get; set; } = null!;
|
||||||
|
}
|
||||||
47
Mlaumcherb.Client.Avalonia/классы/Пролетариат/MyModpackV2.cs
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
using Mlaumcherb.Client.Avalonia.холопы;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
|
||||||
|
public class MyModpackV2
|
||||||
|
{
|
||||||
|
// 2
|
||||||
|
[JsonRequired] public int format_version { get; set; }
|
||||||
|
[JsonRequired] public string name { get; set; } = "";
|
||||||
|
/// relative_path, props
|
||||||
|
// ReSharper disable once CollectionNeverUpdated.Global
|
||||||
|
[JsonRequired] public Dictionary<string, FileProps> files { get; set; } = new();
|
||||||
|
|
||||||
|
|
||||||
|
public class FileProps
|
||||||
|
{
|
||||||
|
[JsonRequired] public Artifact artifact { get; set; } = null!;
|
||||||
|
// disable hash validation, allowing users to edit this file
|
||||||
|
public bool allow_edit { get; set; }
|
||||||
|
// don't re-download file if it was deleted by user
|
||||||
|
public bool optional { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public record FileCheckResult(FileProps props, IOPath relativePath, IOPath absolutePath);
|
||||||
|
public List<FileCheckResult> CheckFiles(IOPath basedir, bool checkHashes, bool downloadOptionalFiles)
|
||||||
|
{
|
||||||
|
List<FileCheckResult> unmatchedFiles = new();
|
||||||
|
IOPath launcherRoot = PathHelper.GetRootFullPath();
|
||||||
|
foreach (var p in files)
|
||||||
|
{
|
||||||
|
if(!downloadOptionalFiles && p.Value.optional)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
IOPath relativePath = new IOPath(p.Key);
|
||||||
|
// libraries can be in modpacks, they are placed in global libraries directory
|
||||||
|
var absolutePath = Path.Concat(relativePath.StartsWith("libraries")
|
||||||
|
? launcherRoot : basedir, relativePath);
|
||||||
|
if (!HashHelper.CheckFileSHA1(absolutePath, p.Value.artifact.sha1, checkHashes && !p.Value.allow_edit))
|
||||||
|
{
|
||||||
|
unmatchedFiles.Add(new FileCheckResult(p.Value, relativePath, absolutePath));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return unmatchedFiles;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
namespace Млаумчерб.Клиент.сеть;
|
namespace Mlaumcherb.Client.Avalonia.сеть;
|
||||||
|
|
||||||
public record struct DataSize(long Bytes)
|
public record struct DataSize(long Bytes)
|
||||||
{
|
{
|
||||||
67
Mlaumcherb.Client.Avalonia/сеть/NetworkHelper.cs
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
using System.Net.Http;
|
||||||
|
using Mlaumcherb.Client.Avalonia.холопы;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.сеть;
|
||||||
|
|
||||||
|
public static class NetworkHelper
|
||||||
|
{
|
||||||
|
private static HttpClient _http = new();
|
||||||
|
|
||||||
|
static NetworkHelper()
|
||||||
|
{
|
||||||
|
// thanks for Sashok :3
|
||||||
|
// https://github.com/new-sashok724/Launcher/blob/23485c3f7de6620d2c6b7b2dd9339c3beb6a0366/Launcher/source/helper/IOHelper.java#L259
|
||||||
|
_http.DefaultRequestHeaders.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
|
||||||
|
_http.Timeout = TimeSpan.FromSeconds(4);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Task<string> GetString(string url, CancellationToken ct = default) => _http.GetStringAsync(url, ct);
|
||||||
|
public static Task<Stream> GetStream(string url, CancellationToken ct = default) => _http.GetStreamAsync(url, ct);
|
||||||
|
|
||||||
|
public static async Task DownloadFile(string url, Stream outStream, CancellationToken ct = default,
|
||||||
|
params TransformStream.TransformFuncDelegate[] transforms)
|
||||||
|
{
|
||||||
|
await using var pipe = new TransformStream(await GetStream(url, ct));
|
||||||
|
if (transforms.Length > 0)
|
||||||
|
pipe.AddTransforms(transforms);
|
||||||
|
await pipe.CopyToAsync(outStream, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task DownloadFile(string url, IOPath outPath, CancellationToken ct = default,
|
||||||
|
params TransformStream.TransformFuncDelegate[] transforms)
|
||||||
|
{
|
||||||
|
await using var file = File.OpenWrite(outPath);
|
||||||
|
await DownloadFile(url, file, ct, transforms);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task<T> DownloadStringAndDeserialize<T>(string url)
|
||||||
|
{
|
||||||
|
var text = await GetString(url);
|
||||||
|
var result = JsonConvert.DeserializeObject<T>(text)
|
||||||
|
?? throw new Exception($"can't deserialize {typeof(T).Name}");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <returns>(file_content, didDownload)</returns>
|
||||||
|
public static async Task<(string, bool)> ReadOrDownload(IOPath filePath, string url,
|
||||||
|
string? sha1, bool checkHashes)
|
||||||
|
{
|
||||||
|
if (HashHelper.CheckFileSHA1(filePath, sha1, checkHashes))
|
||||||
|
return (File.ReadAllText(filePath), false);
|
||||||
|
|
||||||
|
string txt = await NetworkHelper.GetString(url);
|
||||||
|
File.WriteAllText(filePath, txt);
|
||||||
|
return (txt, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <returns>(file_content, didDownload)</returns>
|
||||||
|
public static async Task<(T, bool)> ReadOrDownloadAndDeserialize<T>(IOPath filePath, string url,
|
||||||
|
string? sha1, bool checkHashes)
|
||||||
|
{
|
||||||
|
(string text, bool didDownload) = await ReadOrDownload(filePath, url, sha1, checkHashes);
|
||||||
|
var result = JsonConvert.DeserializeObject<T>(text)
|
||||||
|
?? throw new Exception($"can't deserialize {typeof(T).Name}");
|
||||||
|
return (result, didDownload);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
using Млаумчерб.Клиент.видимое;
|
using Mlaumcherb.Client.Avalonia.зримое;
|
||||||
using Timer = DTLib.Timer;
|
using Timer = DTLib.Timer;
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент.сеть;
|
namespace Mlaumcherb.Client.Avalonia.сеть;
|
||||||
|
|
||||||
public record struct DownloadProgress(DataSize Downloaded, DataSize Total, DataSize PerSecond)
|
public record struct DownloadProgress(DataSize Downloaded, DataSize Total, DataSize PerSecond)
|
||||||
{
|
{
|
||||||
@@ -28,10 +28,9 @@ public class NetworkProgressReporter : IDisposable
|
|||||||
}
|
}
|
||||||
|
|
||||||
// atomic add
|
// atomic add
|
||||||
public void AddBytesCount(ArraySegment<byte> chunk)
|
public void AddBytesCount(byte[] buffer, int offset, int count)
|
||||||
{
|
{
|
||||||
long chunkSize = chunk.Count;
|
Interlocked.Add(ref _curSize, count);
|
||||||
Interlocked.Add(ref _curSize, chunkSize);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Start()
|
public void Start()
|
||||||
@@ -55,7 +54,7 @@ public class NetworkProgressReporter : IDisposable
|
|||||||
long bytesPerSec = (_curSize - _prevSize) / (_timerDelay / 1000);
|
long bytesPerSec = (_curSize - _prevSize) / (_timerDelay / 1000);
|
||||||
_prevSize = _curSize;
|
_prevSize = _curSize;
|
||||||
var p = new DownloadProgress(_curSize, _totalSize, bytesPerSec);
|
var p = new DownloadProgress(_curSize, _totalSize, bytesPerSec);
|
||||||
Приложение.Логгер.LogDebug(nameof(ReportProgress),
|
LauncherApp.Logger.LogDebug(nameof(ReportProgress),
|
||||||
$"download progress {p}");
|
$"download progress {p}");
|
||||||
_reportProgressDelegate(p);
|
_reportProgressDelegate(p);
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
namespace Млаумчерб.Клиент.сеть;
|
namespace Mlaumcherb.Client.Avalonia.сеть;
|
||||||
|
|
||||||
public class NetworkTask : IDisposable
|
public class NetworkTask : IDisposable
|
||||||
{
|
{
|
||||||
@@ -7,7 +7,7 @@ public class NetworkTask : IDisposable
|
|||||||
public enum Status
|
public enum Status
|
||||||
{
|
{
|
||||||
Initialized,
|
Initialized,
|
||||||
Running,
|
Started,
|
||||||
Completed,
|
Completed,
|
||||||
Cancelled,
|
Cancelled,
|
||||||
Failed
|
Failed
|
||||||
@@ -15,6 +15,7 @@ public class NetworkTask : IDisposable
|
|||||||
|
|
||||||
public Status DownloadStatus { get; private set; } = Status.Initialized;
|
public Status DownloadStatus { get; private set; } = Status.Initialized;
|
||||||
|
|
||||||
|
public event Action? OnStart;
|
||||||
public event Action<DownloadProgress>? OnProgress;
|
public event Action<DownloadProgress>? OnProgress;
|
||||||
public event Action<Status>? OnStop;
|
public event Action<Status>? OnStop;
|
||||||
|
|
||||||
@@ -35,15 +36,20 @@ public class NetworkTask : IDisposable
|
|||||||
|
|
||||||
public async Task StartAsync()
|
public async Task StartAsync()
|
||||||
{
|
{
|
||||||
if(DownloadStatus == Status.Running || DownloadStatus == Status.Completed)
|
if(DownloadStatus == Status.Started || DownloadStatus == Status.Completed)
|
||||||
return;
|
return;
|
||||||
DownloadStatus = Status.Running;
|
DownloadStatus = Status.Started;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
_progressReporter.Start();
|
_progressReporter.Start();
|
||||||
|
OnStart?.Invoke();
|
||||||
await _downloadAction(_progressReporter, _cts.Token);
|
await _downloadAction(_progressReporter, _cts.Token);
|
||||||
DownloadStatus = Status.Completed;
|
DownloadStatus = Status.Completed;
|
||||||
}
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
DownloadStatus = Status.Cancelled;
|
||||||
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
DownloadStatus = Status.Failed;
|
DownloadStatus = Status.Failed;
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http;
|
||||||
|
using Mlaumcherb.Client.Avalonia.зримое;
|
||||||
|
using Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
using Mlaumcherb.Client.Avalonia.холопы;
|
||||||
|
using static Mlaumcherb.Client.Avalonia.сеть.NetworkHelper;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.сеть.TaskFactories;
|
||||||
|
|
||||||
|
public class AssetsDownloadTaskFactory : INetworkTaskFactory
|
||||||
|
{
|
||||||
|
private const string ASSET_SERVER_URL = "https://resources.download.minecraft.net/";
|
||||||
|
private GameVersionDescriptor _descriptor;
|
||||||
|
private IOPath _indexFilePath;
|
||||||
|
List<AssetDownloadProperties> _assetsToDownload = new();
|
||||||
|
|
||||||
|
public AssetsDownloadTaskFactory(GameVersionDescriptor descriptor)
|
||||||
|
{
|
||||||
|
_descriptor = descriptor;
|
||||||
|
_indexFilePath = PathHelper.GetAssetIndexFilePath(_descriptor.assetIndex.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<NetworkTask?> CreateAsync(bool checkHashes)
|
||||||
|
{
|
||||||
|
NetworkTask? networkTask = null;
|
||||||
|
if (!await CheckFilesAsync(checkHashes))
|
||||||
|
{
|
||||||
|
networkTask = new NetworkTask(
|
||||||
|
$"assets '{_descriptor.assetIndex.id}'",
|
||||||
|
GetTotalSize(),
|
||||||
|
Download
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return networkTask;
|
||||||
|
}
|
||||||
|
private async Task<bool> CheckFilesAsync(bool checkHashes)
|
||||||
|
{
|
||||||
|
(AssetIndex assetIndex, _) = await ReadOrDownloadAndDeserialize<AssetIndex>(
|
||||||
|
_indexFilePath,
|
||||||
|
_descriptor.assetIndex.url,
|
||||||
|
_descriptor.assetIndex.sha1,
|
||||||
|
checkHashes);
|
||||||
|
|
||||||
|
// removing duplicates for Dictionary (idk how can it be possible, but Newtonsoft.Json creates them)
|
||||||
|
HashSet<string> assetHashes = new HashSet<string>();
|
||||||
|
foreach (var pair in assetIndex.objects)
|
||||||
|
{
|
||||||
|
if (assetHashes.Add(pair.Value.hash))
|
||||||
|
{
|
||||||
|
var a = new AssetDownloadProperties(pair.Key, pair.Value);
|
||||||
|
if (!HashHelper.CheckFileSHA1(a.filePath, a.hash, checkHashes))
|
||||||
|
{
|
||||||
|
_assetsToDownload.Add(a);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return _assetsToDownload.Count == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private long GetTotalSize()
|
||||||
|
{
|
||||||
|
long totalSize = 0;
|
||||||
|
foreach (var a in _assetsToDownload)
|
||||||
|
totalSize += a.size;
|
||||||
|
return totalSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
private class AssetDownloadProperties
|
||||||
|
{
|
||||||
|
public string name;
|
||||||
|
public string hash;
|
||||||
|
public long size;
|
||||||
|
public string url;
|
||||||
|
public IOPath filePath;
|
||||||
|
|
||||||
|
public AssetDownloadProperties(string key, AssetProperties p)
|
||||||
|
{
|
||||||
|
name = key;
|
||||||
|
hash = p.hash;
|
||||||
|
size = p.size;
|
||||||
|
string hashStart = hash.Substring(0, 2);
|
||||||
|
url = $"{ASSET_SERVER_URL}/{hashStart}/{hash}";
|
||||||
|
filePath = Path.Concat(IOPath.ArrayCast(["assets", "objects", hashStart, hash], true));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
|
||||||
|
{
|
||||||
|
LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"started downloading assets '{_descriptor.assetIndex.id}'");
|
||||||
|
ParallelOptions opt = new()
|
||||||
|
{
|
||||||
|
MaxDegreeOfParallelism = LauncherApp.Config.max_parallel_downloads,
|
||||||
|
CancellationToken = ct
|
||||||
|
};
|
||||||
|
await Parallel.ForEachAsync(_assetsToDownload, opt,
|
||||||
|
async (a, _ct) =>
|
||||||
|
{
|
||||||
|
bool completed = false;
|
||||||
|
while(!completed)
|
||||||
|
{
|
||||||
|
LauncherApp.Logger.LogDebug(nameof(NetworkHelper), $"downloading asset '{a.name}' {a.hash}");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await DownloadFile(a.url, a.filePath, _ct, pr.AddBytesCount);
|
||||||
|
completed = true;
|
||||||
|
}
|
||||||
|
catch (HttpRequestException httpException)
|
||||||
|
{
|
||||||
|
// wait on rate limit
|
||||||
|
if(httpException.StatusCode == HttpStatusCode.TooManyRequests)
|
||||||
|
{
|
||||||
|
LauncherApp.Logger.LogDebug(nameof(NetworkHelper), "rate limit hit");
|
||||||
|
await Task.Delay(1000, _ct);
|
||||||
|
}
|
||||||
|
else throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"finished downloading assets '{_descriptor.assetIndex.id}'");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
namespace Млаумчерб.Клиент.сеть.NetworkTaskFactories;
|
namespace Mlaumcherb.Client.Avalonia.сеть.TaskFactories;
|
||||||
|
|
||||||
public interface INetworkTaskFactory
|
public interface INetworkTaskFactory
|
||||||
{
|
{
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
using Mlaumcherb.Client.Avalonia.зримое;
|
||||||
|
using Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
using Mlaumcherb.Client.Avalonia.холопы;
|
||||||
|
using static Mlaumcherb.Client.Avalonia.сеть.NetworkHelper;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.сеть.TaskFactories;
|
||||||
|
|
||||||
|
public class JavaDownloadTaskFactory : INetworkTaskFactory
|
||||||
|
{
|
||||||
|
private const string CATALOG_URL =
|
||||||
|
"https://launchermeta.mojang.com/v1/products/java-runtime/2ec0cc96c44e5a76b9c8b7c39df7210883d12871/all.json";
|
||||||
|
private GameVersionDescriptor _descriptor;
|
||||||
|
private IOPath _javaVersionDir;
|
||||||
|
private JavaDistributiveManifest? _distributiveManifest;
|
||||||
|
private List<(IOPath path, JavaDistributiveElementProps props)> _filesToDownload = new();
|
||||||
|
|
||||||
|
public JavaDownloadTaskFactory(GameVersionDescriptor descriptor)
|
||||||
|
{
|
||||||
|
_descriptor = descriptor;
|
||||||
|
_javaVersionDir = PathHelper.GetJavaRuntimeDir(_descriptor.javaVersion.component);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<NetworkTask?> CreateAsync(bool checkHashes)
|
||||||
|
{
|
||||||
|
var catalog = await DownloadStringAndDeserialize<JavaVersionCatalog>(CATALOG_URL);
|
||||||
|
var versionProps = catalog.GetVersionProps(_descriptor.javaVersion);
|
||||||
|
_distributiveManifest = await DownloadStringAndDeserialize<JavaDistributiveManifest>(versionProps.manifest.url);
|
||||||
|
|
||||||
|
NetworkTask? networkTask = null;
|
||||||
|
if (!CheckFiles(checkHashes))
|
||||||
|
{
|
||||||
|
networkTask = new NetworkTask(
|
||||||
|
$"java runtime '{_descriptor.javaVersion.component}'",
|
||||||
|
GetTotalSize(),
|
||||||
|
Download
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return networkTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool CheckFiles(bool checkHashes)
|
||||||
|
{
|
||||||
|
_filesToDownload.Clear();
|
||||||
|
foreach (var pair in _distributiveManifest!.files)
|
||||||
|
{
|
||||||
|
if (pair.Value.type != "file")
|
||||||
|
continue;
|
||||||
|
|
||||||
|
if (pair.Value.downloads != null)
|
||||||
|
{
|
||||||
|
var artifact = pair.Value.downloads;
|
||||||
|
IOPath file_path = Path.Concat(_javaVersionDir, pair.Key);
|
||||||
|
if (!HashHelper.CheckFileSHA1(file_path, artifact.raw.sha1, checkHashes))
|
||||||
|
{
|
||||||
|
_filesToDownload.Add((file_path, pair.Value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return _filesToDownload.Count == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private long GetTotalSize()
|
||||||
|
{
|
||||||
|
long totalSize = 0;
|
||||||
|
foreach (var file in _filesToDownload)
|
||||||
|
{
|
||||||
|
if(file.props.downloads == null)
|
||||||
|
continue;
|
||||||
|
totalSize += file.props.downloads.lzma?.size ?? file.props.downloads.raw.size;
|
||||||
|
}
|
||||||
|
return totalSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
|
||||||
|
{
|
||||||
|
LauncherApp.Logger.LogInfo(nameof(NetworkHelper), "started downloading java runtime " +
|
||||||
|
$"{_descriptor.javaVersion.majorVersion} '{_descriptor.javaVersion.component}'");
|
||||||
|
|
||||||
|
ParallelOptions opt = new()
|
||||||
|
{
|
||||||
|
MaxDegreeOfParallelism = LauncherApp.Config.max_parallel_downloads,
|
||||||
|
CancellationToken = ct
|
||||||
|
};
|
||||||
|
await Parallel.ForEachAsync(_filesToDownload, opt, async (f, _ct) =>
|
||||||
|
{
|
||||||
|
if (f.props.downloads!.lzma != null)
|
||||||
|
{
|
||||||
|
LauncherApp.Logger.LogDebug(nameof(NetworkHelper), $"downloading lzma-compressed file '{f.path}'");
|
||||||
|
await using var pipe = new TransformStream(await GetStream(f.props.downloads.lzma.url, _ct));
|
||||||
|
pipe.AddTransform(pr.AddBytesCount);
|
||||||
|
await using var fs = File.OpenWrite(f.path);
|
||||||
|
LZMAHelper.Decompress(pipe, fs);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
LauncherApp.Logger.LogDebug(nameof(NetworkHelper), $"downloading raw file '{f.path}'");
|
||||||
|
await DownloadFile(f.props.downloads.raw.url, f.path, _ct, pr.AddBytesCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
if(!OperatingSystem.IsWindows() && f.props.executable is true)
|
||||||
|
{
|
||||||
|
LauncherApp.Logger.LogDebug(nameof(NetworkHelper), $"adding execute rights to file '{f.path}'");
|
||||||
|
System.IO.File.SetUnixFileMode(f.path.ToString(), UnixFileMode.UserExecute);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
LauncherApp.Logger.LogInfo(nameof(NetworkHelper), "finished downloading java runtime " +
|
||||||
|
$"{_descriptor.javaVersion.majorVersion} '{_descriptor.javaVersion.component}'");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
using System.IO.Compression;
|
||||||
|
using Mlaumcherb.Client.Avalonia.зримое;
|
||||||
|
using Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
using Mlaumcherb.Client.Avalonia.холопы;
|
||||||
|
using static Mlaumcherb.Client.Avalonia.сеть.NetworkHelper;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.сеть.TaskFactories;
|
||||||
|
|
||||||
|
public class LibrariesDownloadTaskFactory : INetworkTaskFactory
|
||||||
|
{
|
||||||
|
private GameVersionDescriptor _descriptor;
|
||||||
|
private Libraries _libraries;
|
||||||
|
private List<Libraries.JarLib> _libsToDownload = new();
|
||||||
|
private IOPath _nativesDir;
|
||||||
|
|
||||||
|
public LibrariesDownloadTaskFactory(GameVersionDescriptor descriptor, Libraries libraries)
|
||||||
|
{
|
||||||
|
_descriptor = descriptor;
|
||||||
|
_libraries = libraries;
|
||||||
|
_nativesDir = PathHelper.GetNativeLibrariesDir(descriptor.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<NetworkTask?> CreateAsync(bool checkHashes)
|
||||||
|
{
|
||||||
|
NetworkTask? networkTask = null;
|
||||||
|
if (!CheckFiles(checkHashes))
|
||||||
|
{
|
||||||
|
networkTask = new NetworkTask(
|
||||||
|
$"libraries '{_descriptor.id}'",
|
||||||
|
GetTotalSize(),
|
||||||
|
Download
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Task.FromResult(networkTask);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool CheckFiles(bool checkHashes)
|
||||||
|
{
|
||||||
|
_libsToDownload.Clear();
|
||||||
|
bool nativeDirExists = Directory.Exists(_nativesDir);
|
||||||
|
|
||||||
|
foreach (var l in _libraries.Libs)
|
||||||
|
{
|
||||||
|
if (l is Libraries.NativeLib native)
|
||||||
|
{
|
||||||
|
//TODO: replace with actual native libraries check
|
||||||
|
if(!nativeDirExists || checkHashes)
|
||||||
|
{
|
||||||
|
_libsToDownload.Add(l);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (!HashHelper.CheckFileSHA1(l.jarFilePath, l.artifact?.sha1, checkHashes))
|
||||||
|
{
|
||||||
|
_libsToDownload.Add(l);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return _libsToDownload.Count == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private long GetTotalSize()
|
||||||
|
{
|
||||||
|
long total = 0;
|
||||||
|
foreach (var l in _libsToDownload)
|
||||||
|
total += l.artifact?.size ?? 0;
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
|
||||||
|
{
|
||||||
|
LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"started downloading libraries '{_descriptor.id}'");
|
||||||
|
|
||||||
|
ParallelOptions opt = new()
|
||||||
|
{
|
||||||
|
MaxDegreeOfParallelism = LauncherApp.Config.max_parallel_downloads,
|
||||||
|
CancellationToken = ct
|
||||||
|
};
|
||||||
|
await Parallel.ForEachAsync(_libsToDownload, opt, async (l, _ct) =>
|
||||||
|
{
|
||||||
|
LauncherApp.Logger.LogDebug(nameof(NetworkHelper), $"downloading library '{l.name}' to '{l.jarFilePath}'");
|
||||||
|
if(string.IsNullOrEmpty(l.artifact?.url))
|
||||||
|
throw new Exception($"library '{l.name}' doesn't have a url to download");
|
||||||
|
await DownloadFile(l.artifact.url, l.jarFilePath, _ct, pr.AddBytesCount);
|
||||||
|
if (l is Libraries.NativeLib n)
|
||||||
|
{
|
||||||
|
await using var zipf = File.OpenRead(n.jarFilePath);
|
||||||
|
using var archive = new ZipArchive(zipf);
|
||||||
|
foreach (var entry in archive.Entries)
|
||||||
|
{
|
||||||
|
if (n.extractionOptions?.exclude?.Contains(entry.FullName) is true or null)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
var real_path = Path.Concat(_nativesDir, entry.FullName);
|
||||||
|
Directory.Create(real_path.ParentDir());
|
||||||
|
entry.ExtractToFile(real_path.ToString(), true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"finished downloading libraries '{_descriptor.id}'");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
using Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.сеть.TaskFactories;
|
||||||
|
|
||||||
|
public class ModpackDownloadTaskFactory : INetworkTaskFactory
|
||||||
|
{
|
||||||
|
INetworkTaskFactory _implementationVersion;
|
||||||
|
|
||||||
|
public ModpackDownloadTaskFactory(GameVersionDescriptor descriptor)
|
||||||
|
{
|
||||||
|
if(descriptor.modpack is null)
|
||||||
|
throw new ArgumentNullException(nameof(descriptor.modpack));
|
||||||
|
|
||||||
|
_implementationVersion = descriptor.modpack.format_version switch
|
||||||
|
{
|
||||||
|
2 => new MyModpackV2DownloadTaskFactory(descriptor),
|
||||||
|
_ => throw new Exception($"Unknown Modpack format_version: {descriptor.modpack.format_version}")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<NetworkTask?> CreateAsync(bool checkHashes)
|
||||||
|
{
|
||||||
|
return _implementationVersion.CreateAsync(checkHashes);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
using System.Linq;
|
||||||
|
using Mlaumcherb.Client.Avalonia.зримое;
|
||||||
|
using Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
using Mlaumcherb.Client.Avalonia.холопы;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.сеть.TaskFactories;
|
||||||
|
|
||||||
|
public class MyModpackV2DownloadTaskFactory : INetworkTaskFactory
|
||||||
|
{
|
||||||
|
private readonly GameVersionDescriptor _descriptor;
|
||||||
|
private IOPath _modpackDescriptorPath;
|
||||||
|
private IOPath _versionDir;
|
||||||
|
private MyModpackV2? _modpack;
|
||||||
|
// relative, absolute
|
||||||
|
private List<MyModpackV2.FileCheckResult> _filesToDownload = new();
|
||||||
|
|
||||||
|
public MyModpackV2DownloadTaskFactory(GameVersionDescriptor descriptor)
|
||||||
|
{
|
||||||
|
_descriptor = descriptor;
|
||||||
|
_modpackDescriptorPath = PathHelper.GetModpackDescriptorPath(_descriptor.id);
|
||||||
|
_versionDir = PathHelper.GetVersionDir(_descriptor.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<NetworkTask?> CreateAsync(bool checkHashes)
|
||||||
|
{
|
||||||
|
if(_descriptor.modpack is null)
|
||||||
|
throw new ArgumentNullException(nameof(_descriptor.modpack));
|
||||||
|
|
||||||
|
(_modpack, bool didDownloadModpackDescriptor) = await NetworkHelper.ReadOrDownloadAndDeserialize<MyModpackV2>(
|
||||||
|
_modpackDescriptorPath,
|
||||||
|
_descriptor.modpack.artifact.url,
|
||||||
|
_descriptor.modpack.artifact.sha1,
|
||||||
|
checkHashes);
|
||||||
|
if (_modpack.format_version != _descriptor.modpack.format_version)
|
||||||
|
throw new Exception($"Modpack.format_version mismatches descriptor.modpack.version: " +
|
||||||
|
$"{_modpack.format_version} != {_descriptor.modpack.format_version}");
|
||||||
|
|
||||||
|
NetworkTask? networkTask = null;
|
||||||
|
_filesToDownload = _modpack.CheckFiles(_versionDir, checkHashes, didDownloadModpackDescriptor);
|
||||||
|
if(_filesToDownload.Count > 0)
|
||||||
|
{
|
||||||
|
networkTask = new NetworkTask(
|
||||||
|
$"modpack '{_modpack.name}'",
|
||||||
|
_filesToDownload.Sum(f => f.props.artifact.size),
|
||||||
|
Download
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return networkTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
|
||||||
|
{
|
||||||
|
LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"started downloading modpack '{_modpack!.name}'");
|
||||||
|
|
||||||
|
ParallelOptions opt = new()
|
||||||
|
{
|
||||||
|
MaxDegreeOfParallelism = LauncherApp.Config.max_parallel_downloads,
|
||||||
|
CancellationToken = ct
|
||||||
|
};
|
||||||
|
await Parallel.ForEachAsync(_filesToDownload, opt, async (f, _ct) =>
|
||||||
|
{
|
||||||
|
LauncherApp.Logger.LogDebug(nameof(NetworkHelper), $"downloading file '{f.relativePath}'");
|
||||||
|
if(string.IsNullOrEmpty(f.props.artifact.url))
|
||||||
|
throw new Exception($"file '{f.relativePath}' doesn't have a url to download");
|
||||||
|
await NetworkHelper.DownloadFile(f.props.artifact.url, f.absolutePath, _ct, pr.AddBytesCount);
|
||||||
|
});
|
||||||
|
|
||||||
|
LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"finished downloading modpack '{_modpack.name}'");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
using Mlaumcherb.Client.Avalonia.зримое;
|
||||||
|
using Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
using Mlaumcherb.Client.Avalonia.холопы;
|
||||||
|
using static Mlaumcherb.Client.Avalonia.сеть.NetworkHelper;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.сеть.TaskFactories;
|
||||||
|
|
||||||
|
public class VersionJarDownloadTaskFactory : INetworkTaskFactory
|
||||||
|
{
|
||||||
|
private GameVersionDescriptor _descriptor;
|
||||||
|
private IOPath _filePath;
|
||||||
|
|
||||||
|
public VersionJarDownloadTaskFactory(GameVersionDescriptor descriptor)
|
||||||
|
{
|
||||||
|
_descriptor = descriptor;
|
||||||
|
_filePath = PathHelper.GetVersionJarFilePath(_descriptor.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<NetworkTask?> CreateAsync(bool checkHashes)
|
||||||
|
{
|
||||||
|
NetworkTask? networkTask = null;
|
||||||
|
if (!CheckFiles(checkHashes))
|
||||||
|
{
|
||||||
|
networkTask = new NetworkTask(
|
||||||
|
$"game version jar '{_descriptor.id}'",
|
||||||
|
GetTotalSize(),
|
||||||
|
Download
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Task.FromResult(networkTask);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool CheckFiles(bool checkHashes)
|
||||||
|
{
|
||||||
|
return HashHelper.CheckFileSHA1(_filePath, _descriptor.downloads?.client.sha1, checkHashes);
|
||||||
|
}
|
||||||
|
|
||||||
|
private long GetTotalSize()
|
||||||
|
{
|
||||||
|
if(_descriptor.downloads is null)
|
||||||
|
return 0;
|
||||||
|
return _descriptor.downloads.client.size;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (_descriptor.downloads is null)
|
||||||
|
throw new Exception($"can't download game version jar '{_descriptor.id}' because it has no download url");
|
||||||
|
|
||||||
|
LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"started downloading game version jar '{_descriptor.id}'");
|
||||||
|
await DownloadFile(_descriptor.downloads.client.url, _filePath, ct, pr.AddBytesCount);
|
||||||
|
LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"finished downloading game version jar '{_descriptor.id}'");
|
||||||
|
}
|
||||||
|
}
|
||||||
38
Mlaumcherb.Client.Avalonia/сеть/Update/Gitea.cs
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
using System.Linq;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.сеть.Update;
|
||||||
|
|
||||||
|
public class Release
|
||||||
|
{
|
||||||
|
[JsonRequired] public int id { get; set; }
|
||||||
|
[JsonRequired] public string tag_name { get; set; } = "";
|
||||||
|
[JsonRequired] public DateTime created_at { get; set; }
|
||||||
|
// ReSharper disable once CollectionNeverUpdated.Global
|
||||||
|
public List<Asset> assets { get; set; } = new();
|
||||||
|
|
||||||
|
public class Asset
|
||||||
|
{
|
||||||
|
[JsonRequired] public int id { get; set; }
|
||||||
|
[JsonRequired] public string name { get; set; } = "";
|
||||||
|
[JsonRequired] public int size { get; set; }
|
||||||
|
[JsonRequired] public DateTime created_at { get; set; }
|
||||||
|
[JsonRequired] public string browser_download_url { get; set; } = "";
|
||||||
|
|
||||||
|
public async Task Download(IOPath localPath)
|
||||||
|
{
|
||||||
|
await NetworkHelper.DownloadFile(browser_download_url, localPath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Asset? FindAssetByName(string name) =>
|
||||||
|
assets.FirstOrDefault(a => a.name == name);
|
||||||
|
}
|
||||||
|
|
||||||
|
public class GiteaClient(string ServerUrl)
|
||||||
|
{
|
||||||
|
public async Task<Release> GetLatestRelease(string user, string repo)
|
||||||
|
{
|
||||||
|
string url = $"{ServerUrl}/api/v1/repos/{user}/{repo}/releases/latest";
|
||||||
|
return await NetworkHelper.DownloadStringAndDeserialize<Release>(url);
|
||||||
|
}
|
||||||
|
}
|
||||||
76
Mlaumcherb.Client.Avalonia/сеть/Update/UpdateHelper.cs
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
using System.Reflection;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.сеть.Update;
|
||||||
|
|
||||||
|
public class UpdateHelper
|
||||||
|
{
|
||||||
|
private readonly string _executableName = "млаумчерб.exe";
|
||||||
|
private readonly IOPath executablePathActual;
|
||||||
|
private readonly IOPath executablePathOld;
|
||||||
|
private readonly IOPath executablePathNew;
|
||||||
|
|
||||||
|
private readonly GiteaConfig _giteaConfig;
|
||||||
|
|
||||||
|
public class GiteaConfig
|
||||||
|
{
|
||||||
|
[JsonRequired] public required string serverUrl { get; set; }
|
||||||
|
[JsonRequired] public required string user { get; set; }
|
||||||
|
[JsonRequired] public required string repo { get; set; }
|
||||||
|
|
||||||
|
public string GetRepoUrl() => $"{serverUrl}/{user}/{repo}";
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public UpdateHelper(GiteaConfig giteaConfig)
|
||||||
|
{
|
||||||
|
_giteaConfig = giteaConfig;
|
||||||
|
executablePathActual = _executableName;
|
||||||
|
executablePathOld = _executableName + ".old";
|
||||||
|
executablePathNew = _executableName + ".new";
|
||||||
|
Gitea = new GiteaClient(giteaConfig.serverUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
public GiteaClient Gitea { get; }
|
||||||
|
|
||||||
|
public void DeleteBackupFiles()
|
||||||
|
{
|
||||||
|
if(File.Exists(executablePathOld))
|
||||||
|
File.Delete(executablePathOld);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> IsUpdateAvailable()
|
||||||
|
{
|
||||||
|
var latest = await Gitea.GetLatestRelease(_giteaConfig.user, _giteaConfig.repo);
|
||||||
|
if (!Version.TryParse(latest.tag_name, out var latestVersion))
|
||||||
|
throw new Exception($"Can't parse version of latest release: {latest.tag_name}");
|
||||||
|
|
||||||
|
Version? currentVersion = Assembly.GetExecutingAssembly().GetName().Version;
|
||||||
|
if(currentVersion is null)
|
||||||
|
throw new Exception($"Can't get current version from {Assembly.GetExecutingAssembly().GetName()}");
|
||||||
|
|
||||||
|
return currentVersion < latestVersion;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task UpdateSelf()
|
||||||
|
{
|
||||||
|
if(File.Exists(executablePathNew))
|
||||||
|
File.Delete(executablePathNew);
|
||||||
|
|
||||||
|
var latest = await Gitea.GetLatestRelease(_giteaConfig.user, _giteaConfig.repo);
|
||||||
|
var asset = latest.FindAssetByName(_executableName);
|
||||||
|
if(asset == null)
|
||||||
|
throw new Exception($"Can't find updated executable on gitea: {_executableName}");
|
||||||
|
await asset.Download(executablePathNew);
|
||||||
|
|
||||||
|
File.Move(executablePathActual, executablePathOld, true);
|
||||||
|
File.Move(executablePathNew, executablePathActual, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void RestartSelf()
|
||||||
|
{
|
||||||
|
Process.Start(executablePathActual.ToString());
|
||||||
|
Thread.Sleep(500);
|
||||||
|
Environment.Exit(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,21 +1,21 @@
|
|||||||
using Avalonia.Controls;
|
using Avalonia.Controls;
|
||||||
using DTLib.Demystifier;
|
using DTLib.Demystifier;
|
||||||
|
using Mlaumcherb.Client.Avalonia.зримое;
|
||||||
using MsBox.Avalonia;
|
using MsBox.Avalonia;
|
||||||
using MsBox.Avalonia.Dto;
|
using MsBox.Avalonia.Dto;
|
||||||
using MsBox.Avalonia.Enums;
|
using MsBox.Avalonia.Enums;
|
||||||
using MsBox.Avalonia.Models;
|
using MsBox.Avalonia.Models;
|
||||||
using Млаумчерб.Клиент.видимое;
|
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент;
|
namespace Mlaumcherb.Client.Avalonia.холопы;
|
||||||
|
|
||||||
public static class Ошибки
|
public static class ErrorHelper
|
||||||
{
|
{
|
||||||
internal static void ПоказатьСообщение(string context, Exception err)
|
internal static void ShowMessageBox(string context, Exception err)
|
||||||
=> ПоказатьСообщение(context, err.ToStringDemystified());
|
=> ShowMessageBox(context, err.ToStringDemystified());
|
||||||
|
|
||||||
internal static async void ПоказатьСообщение(string context, string err)
|
internal static async void ShowMessageBox(string context, string err)
|
||||||
{
|
{
|
||||||
Приложение.Логгер.LogError(nameof(Ошибки), err);
|
LauncherApp.Logger.LogError(context, err);
|
||||||
var box = MessageBoxManager.GetMessageBoxCustom(new MessageBoxCustomParams
|
var box = MessageBoxManager.GetMessageBoxCustom(new MessageBoxCustomParams
|
||||||
{
|
{
|
||||||
ButtonDefinitions = new List<ButtonDefinition> { new() { Name = "пон" } },
|
ButtonDefinitions = new List<ButtonDefinition> { new() { Name = "пон" } },
|
||||||
32
Mlaumcherb.Client.Avalonia/холопы/HashHelper.cs
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
|
using DTLib.Extensions;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.холопы;
|
||||||
|
|
||||||
|
public static class HashHelper
|
||||||
|
{
|
||||||
|
private static SHA1 _hasher;
|
||||||
|
|
||||||
|
static HashHelper()
|
||||||
|
{
|
||||||
|
_hasher = SHA1.Create();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string HashFileSHA1(IOPath f)
|
||||||
|
{
|
||||||
|
using var fs = File.OpenRead(f);
|
||||||
|
byte[] hash = _hasher.ComputeHash(fs);
|
||||||
|
return hash.HashToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool CheckFileSHA1(IOPath f, string? sha1, bool checkHash)
|
||||||
|
{
|
||||||
|
if (!File.Exists(f))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if(checkHash && sha1 is not null)
|
||||||
|
return HashFileSHA1(f) == sha1;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
26
Mlaumcherb.Client.Avalonia/холопы/LZMAHelper.cs
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
namespace Mlaumcherb.Client.Avalonia.холопы;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// https://gist.github.com/ststeiger/cb9750664952f775a341
|
||||||
|
/// </summary>
|
||||||
|
public static class LZMAHelper
|
||||||
|
{
|
||||||
|
public static void Decompress(Stream inputStream, Stream outputStream)
|
||||||
|
{
|
||||||
|
var decoder = new SevenZip.Compression.LZMA.Decoder();
|
||||||
|
var properties = new byte[5];
|
||||||
|
// Read decoder properties
|
||||||
|
if (inputStream.Read(properties, 0, 5) != 5)
|
||||||
|
throw new Exception("lzma stream is too short");
|
||||||
|
decoder.SetDecoderProperties(properties);
|
||||||
|
|
||||||
|
// Read decompressed data size
|
||||||
|
var fileLengthBytes = new byte[8];
|
||||||
|
if(inputStream.Read(fileLengthBytes, 0, 8) != 8)
|
||||||
|
throw new Exception("lzma stream is too short");
|
||||||
|
long fileLength = BitConverter.ToInt64(fileLengthBytes, 0);
|
||||||
|
|
||||||
|
// Decode
|
||||||
|
decoder.Code(inputStream, outputStream, -1, fileLength, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
68
Mlaumcherb.Client.Avalonia/холопы/PathHelper.cs
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
using Mlaumcherb.Client.Avalonia.зримое;
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.холопы;
|
||||||
|
|
||||||
|
public static class PathHelper
|
||||||
|
{
|
||||||
|
public static IOPath GetRootFullPath() =>
|
||||||
|
System.IO.Path.GetFullPath(new IOPath(LauncherApp.Config.minecraft_dir).ToString());
|
||||||
|
|
||||||
|
public static IOPath GetAssetsDir() =>
|
||||||
|
Path.Concat(GetRootFullPath(), "assets");
|
||||||
|
|
||||||
|
public static IOPath GetAssetIndexFilePath(string id) =>
|
||||||
|
Path.Concat(GetAssetsDir(), $"indexes/{id}.json"); // this path is hardcoded in the game
|
||||||
|
|
||||||
|
public static IOPath GetVersionDescriptorPath(string id) =>
|
||||||
|
Path.Concat(GetVersionDir(id), id + ".json");
|
||||||
|
|
||||||
|
public static IOPath GetVersionsDir() =>
|
||||||
|
Path.Concat(GetRootFullPath(), "versions");
|
||||||
|
|
||||||
|
public static IOPath GetVersionDir(string id) =>
|
||||||
|
Path.Concat(GetVersionsDir(), id);
|
||||||
|
|
||||||
|
public static IOPath GetVersionJarFilePath(string id) =>
|
||||||
|
Path.Concat(GetVersionDir(id), id + ".jar");
|
||||||
|
|
||||||
|
public static IOPath GetLibrariesDir() =>
|
||||||
|
Path.Concat(GetRootFullPath(), "libraries");
|
||||||
|
|
||||||
|
public static IOPath GetNativeLibrariesDir(string id) =>
|
||||||
|
Path.Concat(GetVersionDir(id), "natives", PlatformHelper.GetOsAndArch());
|
||||||
|
|
||||||
|
public static IOPath GetJavaRuntimesDir() =>
|
||||||
|
Path.Concat(GetRootFullPath(), "java");
|
||||||
|
|
||||||
|
|
||||||
|
public static IOPath GetJavaRuntimeDir(string id) =>
|
||||||
|
Path.Concat(GetJavaRuntimesDir(), PlatformHelper.GetOsAndArch(), id);
|
||||||
|
|
||||||
|
public static IOPath GetJavaBinDir(string id) =>
|
||||||
|
Path.Concat(GetJavaRuntimeDir(id), "bin");
|
||||||
|
public static IOPath GetJavaExecutablePath(string id, bool redirectOutput)
|
||||||
|
{
|
||||||
|
string executable_name = "java";
|
||||||
|
if (!redirectOutput)
|
||||||
|
executable_name = "javaw";
|
||||||
|
if(OperatingSystem.IsWindows())
|
||||||
|
executable_name += ".exe";
|
||||||
|
var path = Path.Concat(GetJavaBinDir(id), executable_name);
|
||||||
|
if(!redirectOutput && !File.Exists(path))
|
||||||
|
return GetJavaExecutablePath(id, true);
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string GetLog4jConfigFileName() => "log4j.xml";
|
||||||
|
|
||||||
|
public static IOPath GetLog4jConfigFilePath() =>
|
||||||
|
Path.Concat(GetAssetsDir(), GetLog4jConfigFileName());
|
||||||
|
|
||||||
|
public static IOPath GetModpackDescriptorPath(string game_version) =>
|
||||||
|
Path.Concat(GetVersionDir(game_version), "timerix_modpack.json");
|
||||||
|
|
||||||
|
public static IOPath GetCacheDir() =>
|
||||||
|
Path.Concat(GetRootFullPath(), "cache");
|
||||||
|
public static IOPath GetInstalledVersionCatalogPath() =>
|
||||||
|
Path.Concat(GetCacheDir(), "installed_versions.json");
|
||||||
|
}
|
||||||
55
Mlaumcherb.Client.Avalonia/холопы/PlatformHelper.cs
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using Mlaumcherb.Client.Avalonia.классы;
|
||||||
|
|
||||||
|
// ReSharper disable CollectionNeverUpdated.Global
|
||||||
|
|
||||||
|
namespace Mlaumcherb.Client.Avalonia.холопы;
|
||||||
|
|
||||||
|
public static class PlatformHelper
|
||||||
|
{
|
||||||
|
public static bool CheckOs(Os os) =>
|
||||||
|
os.name switch
|
||||||
|
{
|
||||||
|
null => true,
|
||||||
|
"osx" => OperatingSystem.IsMacOS(),
|
||||||
|
"linux" => OperatingSystem.IsLinux(),
|
||||||
|
"windows" => OperatingSystem.IsWindows(),
|
||||||
|
_ => throw new ArgumentOutOfRangeException(os.name)
|
||||||
|
}
|
||||||
|
&& os.arch switch
|
||||||
|
{
|
||||||
|
null => true,
|
||||||
|
"i386" or "x86" => RuntimeInformation.OSArchitecture == Architecture.X86,
|
||||||
|
"x64" => RuntimeInformation.OSArchitecture == Architecture.X64,
|
||||||
|
"arm64" => RuntimeInformation.OSArchitecture == Architecture.Arm64,
|
||||||
|
_ => false
|
||||||
|
};
|
||||||
|
|
||||||
|
public static string GetOs() =>
|
||||||
|
Environment.OSVersion.Platform switch
|
||||||
|
{
|
||||||
|
PlatformID.Win32NT => "windows",
|
||||||
|
PlatformID.Unix => "linux",
|
||||||
|
PlatformID.MacOSX => "osx",
|
||||||
|
_ => throw new PlatformNotSupportedException("OS not supported")
|
||||||
|
};
|
||||||
|
|
||||||
|
public static string GetArch() =>
|
||||||
|
RuntimeInformation.OSArchitecture switch
|
||||||
|
{
|
||||||
|
Architecture.X86 => "x86",
|
||||||
|
Architecture.X64 => "x64",
|
||||||
|
Architecture.Arm64 => "arm64",
|
||||||
|
_ => throw new PlatformNotSupportedException("OS not supported")
|
||||||
|
};
|
||||||
|
|
||||||
|
public static string GetArchOld() =>
|
||||||
|
RuntimeInformation.OSArchitecture switch
|
||||||
|
{
|
||||||
|
Architecture.X86 => "32",
|
||||||
|
Architecture.X64 => "64",
|
||||||
|
_ => throw new PlatformNotSupportedException("OS not supported")
|
||||||
|
};
|
||||||
|
|
||||||
|
public static string GetOsAndArch() => GetOs() + '-' + GetArch();
|
||||||
|
}
|
||||||
12
Mlaumcherb.Client.Avalonia/холопы/ReverseComparer.cs
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
namespace Mlaumcherb.Client.Avalonia.холопы;
|
||||||
|
|
||||||
|
// compares Y with X instead of X with Y
|
||||||
|
public class ReverseComparer<T> : IComparer<T> where T : IComparable<T>
|
||||||
|
{
|
||||||
|
public int Compare(T? x, T? y)
|
||||||
|
{
|
||||||
|
if (y is null)
|
||||||
|
return x is null ? 0 : -1;
|
||||||
|
return y.CompareTo(x);
|
||||||
|
}
|
||||||
|
}
|
||||||
14
README.md
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
# Mlaumcherb - a minecraft laumcherb
|
||||||
|
|
||||||
|
<img src="./images/cheems.png" alt="silly-dog-picture" style="width:200px;"/>
|
||||||
|
|
||||||
|
## Features
|
||||||
|
- Downloads minecraft from mojang server or any other
|
||||||
|
- Downloads java or uses whatever you specified in config
|
||||||
|
- Downloads modpacks of my custom format
|
||||||
|
- Automatic launcher updates from git releases
|
||||||
|
|
||||||
|
## How to build
|
||||||
|
```sh
|
||||||
|
./build.sh selfcontained
|
||||||
|
```
|
||||||
@@ -29,19 +29,21 @@ case "$mode" in
|
|||||||
args="$args_selfcontained"
|
args="$args_selfcontained"
|
||||||
;;
|
;;
|
||||||
*)
|
*)
|
||||||
echo "ПОЛЬЗОВАНИЕ: ./собрать.sh [способ]"
|
echo "ПОЛЬЗОВАНИЕ: ./build.sh [способ]"
|
||||||
echo " СПОСОБЫ:"
|
echo " СПОСОБЫ:"
|
||||||
echo " бинарное - компилирует промежуточный (управляемый) код в машинный вместе с рантаймом"
|
echo " aot, native, бинарное - компилирует промежуточный (управляемый) код в машинный вместе с рантаймом"
|
||||||
echo " небинарное - приделывает промежуточный (управляемый) код к рантайму"
|
echo " self-contained, selfcontained, небинарное - приделывает промежуточный (управляемый) код к рантайму"
|
||||||
echo " Оба способа собирают программу в один файл, который не является 80-мегабайтовым умственно отсталым кубом. Он 20-мегабайтовый >w<"
|
echo " Оба способа собирают программу в один файл, который не является 80-мегабайтовым умственно отсталым кубом.\
|
||||||
|
Он 20-мегабайтовый >w<"
|
||||||
exit 1
|
exit 1
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
rm -rf "$outdir"
|
rm -rf "$outdir"
|
||||||
|
# when internet breaks again add --source /mnt/c/Users/User/.nuget/packages/
|
||||||
command="dotnet publish -c Release -o $outdir $args"
|
command="dotnet publish -c Release -o $outdir $args"
|
||||||
echo "$command"
|
echo "$command"
|
||||||
$command
|
$command
|
||||||
|
|
||||||
find "$outdir" -name '*.pdb' -delete -printf "deleted '%p'\n"
|
find "$outdir" -name '*.pdb' -delete -printf "deleted '%p'\n"
|
||||||
ls -shk "$outdir" | sort -h
|
tree -sh "$outdir"
|
||||||
BIN
images/cheems.png
Normal file
|
After Width: | Height: | Size: 19 KiB |
@@ -1,10 +1,12 @@
|
|||||||
|
|
||||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Млаумчерб.Клиент", "Млаумчерб.Клиент\Млаумчерб.Клиент.csproj", "{9B9D8B05-255F-49C3-89EC-3F43A66491D3}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mlaumcherb.Client.Avalonia", "Mlaumcherb.Client.Avalonia\Mlaumcherb.Client.Avalonia.csproj", "{9B9D8B05-255F-49C3-89EC-3F43A66491D3}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SolutionFolder", "SolutionFolder", "{A3217C18-CC0D-4CE8-9C48-1BDEC1E1B333}"
|
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SolutionFolder", "SolutionFolder", "{A3217C18-CC0D-4CE8-9C48-1BDEC1E1B333}"
|
||||||
ProjectSection(SolutionItems) = preProject
|
ProjectSection(SolutionItems) = preProject
|
||||||
nuget.config = nuget.config
|
.gitignore = .gitignore
|
||||||
|
README.md = README.md
|
||||||
|
build.sh = build.sh
|
||||||
EndProjectSection
|
EndProjectSection
|
||||||
EndProject
|
EndProject
|
||||||
Global
|
Global
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<configuration>
|
|
||||||
<packageSources>
|
|
||||||
<!-- avalonia nightly feed -->
|
|
||||||
<add key="avalonia-nightly" value="https://nuget-feed-nightly.avaloniaui.net/v3/index.json" protocolVersion="3" />
|
|
||||||
</packageSources>
|
|
||||||
</configuration>
|
|
||||||
@@ -1,132 +0,0 @@
|
|||||||
using CliWrap;
|
|
||||||
using DTLib.Extensions;
|
|
||||||
using Млаумчерб.Клиент.видимое;
|
|
||||||
using Млаумчерб.Клиент.классы;
|
|
||||||
using Млаумчерб.Клиент.сеть;
|
|
||||||
using Млаумчерб.Клиент.сеть.NetworkTaskFactories;
|
|
||||||
using static Млаумчерб.Клиент.классы.Пути;
|
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент;
|
|
||||||
|
|
||||||
public class GameVersion
|
|
||||||
{
|
|
||||||
private readonly GameVersionProps _props;
|
|
||||||
public string Name => _props.Name;
|
|
||||||
public IOPath WorkingDirectory { get; }
|
|
||||||
|
|
||||||
private IOPath JavaExecutableFilePath;
|
|
||||||
|
|
||||||
private GameVersionDescriptor descriptor;
|
|
||||||
private JavaArguments javaArgs;
|
|
||||||
private GameArguments gameArgs;
|
|
||||||
private Libraries libraries;
|
|
||||||
private CancellationTokenSource? gameCts;
|
|
||||||
private CommandTask<CommandResult>? commandTask;
|
|
||||||
|
|
||||||
public static async Task<List<GameVersionProps>> GetAllVersionsAsync()
|
|
||||||
{
|
|
||||||
var propsList = new List<GameVersionProps>();
|
|
||||||
foreach (IOPath f in Directory.GetFiles(GetVersionDescriptorDir()))
|
|
||||||
{
|
|
||||||
string name = GetVersionDescriptorName(f);
|
|
||||||
propsList.Add(new GameVersionProps(name, null, f));
|
|
||||||
}
|
|
||||||
|
|
||||||
var remoteVersions = await Сеть.GetDownloadableVersions();
|
|
||||||
propsList.AddRange(remoteVersions);
|
|
||||||
return propsList;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static async Task<GameVersion> CreateFromPropsAsync(GameVersionProps props)
|
|
||||||
{
|
|
||||||
if (!File.Exists(props.LocalDescriptorPath))
|
|
||||||
{
|
|
||||||
if (props.RemoteDescriptorUrl is null)
|
|
||||||
throw new NullReferenceException("can't download game version descriptor '"
|
|
||||||
+ props.Name + "', because RemoteDescriptorUrl is null");
|
|
||||||
await Сеть.DownloadFileHTTP(props.RemoteDescriptorUrl, props.LocalDescriptorPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
return new GameVersion(props);
|
|
||||||
}
|
|
||||||
|
|
||||||
private GameVersion(GameVersionProps props)
|
|
||||||
{
|
|
||||||
_props = props;
|
|
||||||
string descriptorText = File.ReadAllText(props.LocalDescriptorPath);
|
|
||||||
descriptor = JsonConvert.DeserializeObject<GameVersionDescriptor>(descriptorText)
|
|
||||||
?? throw new Exception($"can't parse descriptor file '{props.LocalDescriptorPath}'");
|
|
||||||
javaArgs = new JavaArguments(descriptor);
|
|
||||||
gameArgs = new GameArguments(descriptor);
|
|
||||||
libraries = new Libraries(descriptor);
|
|
||||||
WorkingDirectory = GetVersionDir(descriptor.id);
|
|
||||||
JavaExecutableFilePath = GetJavaExecutablePath(descriptor.javaVersion.component);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<List<NetworkTask>> CreateUpdateTasksAsync(bool checkHashes)
|
|
||||||
{
|
|
||||||
List<INetworkTaskFactory> taskFactories =
|
|
||||||
[
|
|
||||||
new AssetsDownloadTaskFactory(descriptor),
|
|
||||||
new LibrariesDownloadTaskFactory(descriptor, libraries),
|
|
||||||
new VersionFileDownloadTaskFactory(descriptor),
|
|
||||||
];
|
|
||||||
/*if(Приложение.Настройки.скачать_жабу)
|
|
||||||
{
|
|
||||||
taskFactories.Add(new JavaDownloadTaskFactory(descriptor));
|
|
||||||
}*/
|
|
||||||
/*if (modpack != null)
|
|
||||||
{
|
|
||||||
taskFactories.Add(new ModpackDownloadTaskFactory(modpack));
|
|
||||||
}*/
|
|
||||||
|
|
||||||
List<NetworkTask> tasks = new();
|
|
||||||
for (int i = 0; i < taskFactories.Count; i++)
|
|
||||||
{
|
|
||||||
var nt = await taskFactories[i].CreateAsync(checkHashes);
|
|
||||||
if (nt != null)
|
|
||||||
tasks.Add(nt);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (tasks.Count == 0)
|
|
||||||
{
|
|
||||||
_props.IsDownloaded = true;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
tasks[^1].OnStop += status =>
|
|
||||||
{
|
|
||||||
if (status == NetworkTask.Status.Completed)
|
|
||||||
_props.IsDownloaded = true;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return tasks;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task Launch()
|
|
||||||
{
|
|
||||||
var javaArgsList = javaArgs.FillPlaceholders([]);
|
|
||||||
var gameArgsList = gameArgs.FillPlaceholders([]);
|
|
||||||
var command = Cli.Wrap(JavaExecutableFilePath.ToString())
|
|
||||||
.WithWorkingDirectory(WorkingDirectory.ToString())
|
|
||||||
.WithArguments(javaArgsList)
|
|
||||||
.WithArguments(gameArgsList);
|
|
||||||
Приложение.Логгер.LogInfo(nameof(GameVersion),
|
|
||||||
$"launching the game" +
|
|
||||||
"\njava: " + command.TargetFilePath +
|
|
||||||
"\nworking_dir: " + command.WorkingDirPath +
|
|
||||||
"\njava_arguments: \n\t" + javaArgsList.MergeToString("\n\t") +
|
|
||||||
"\ngame_arguments: \n\t" + gameArgsList.MergeToString("\n\t"));
|
|
||||||
gameCts = new();
|
|
||||||
commandTask = command.ExecuteAsync(gameCts.Token);
|
|
||||||
var result = await commandTask;
|
|
||||||
Приложение.Логгер.LogInfo(nameof(GameVersion), $"game exited with code {result.ExitCode}");
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Close()
|
|
||||||
{
|
|
||||||
gameCts?.Cancel();
|
|
||||||
}
|
|
||||||
|
|
||||||
public override string ToString() => Name;
|
|
||||||
}
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
using DTLib.Extensions;
|
|
||||||
using Млаумчерб.Клиент.видимое;
|
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент;
|
|
||||||
|
|
||||||
public record Настройки
|
|
||||||
{
|
|
||||||
public string имя_пользователя { get; set; } = "";
|
|
||||||
public int выделенная_память_мб { get; set; } = 4096;
|
|
||||||
public bool открывать_на_весь_экран { get; set; }
|
|
||||||
public string путь_к_кубачу { get; set; } = ".";
|
|
||||||
public bool скачать_жабу { get; set; } = true;
|
|
||||||
public string? последняя_запущенная_версия { get; set; }
|
|
||||||
|
|
||||||
[JsonIgnore] private Stream? fileWriteStream;
|
|
||||||
|
|
||||||
public static Настройки ЗагрузитьИзФайла(string имя_файла = "млаумчерб.настройки")
|
|
||||||
{
|
|
||||||
Приложение.Логгер.LogInfo(nameof(Настройки), $"загружаются настройки из файла '{имя_файла}'");
|
|
||||||
if(!File.Exists(имя_файла))
|
|
||||||
{
|
|
||||||
Приложение.Логгер.LogInfo(nameof(Настройки), "файл не существует");
|
|
||||||
return new Настройки();
|
|
||||||
}
|
|
||||||
|
|
||||||
string текст = File.ReadAllText(имя_файла);
|
|
||||||
Настройки? н = JsonConvert.DeserializeObject<Настройки>(текст);
|
|
||||||
if (н == null)
|
|
||||||
{
|
|
||||||
File.Move(имя_файла, имя_файла + ".старые", true);
|
|
||||||
Ошибки.ПоказатьСообщение("Настройки", $"Не удалось прочитать настройки.\n" +
|
|
||||||
$"Сломанный файл настроек переименован в '{имя_файла}.старые'.\n" +
|
|
||||||
$"Создаётся новый файл '{имя_файла}'.");
|
|
||||||
н = new Настройки();
|
|
||||||
н.СохранитьВФайл();
|
|
||||||
}
|
|
||||||
|
|
||||||
Приложение.Логгер.LogInfo(nameof(Настройки), $"настройки загружены: {н}");
|
|
||||||
return н;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void СохранитьВФайл(string имя_файла = "млаумчерб.настройки")
|
|
||||||
{
|
|
||||||
//TODO: file backup and restore
|
|
||||||
Приложение.Логгер.LogDebug(nameof(Настройки), $"настройки сохраняются в файл '{имя_файла}'");
|
|
||||||
fileWriteStream ??= File.OpenWrite(имя_файла);
|
|
||||||
var текст = JsonConvert.SerializeObject(this, Formatting.Indented);
|
|
||||||
fileWriteStream.Seek(0, SeekOrigin.Begin);
|
|
||||||
fileWriteStream.FluentWriteString(текст).Flush();
|
|
||||||
Приложение.Логгер.LogDebug(nameof(Настройки), $"настройки сохранены: {текст}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
<UserControl xmlns="https://github.com/avaloniaui"
|
|
||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
|
||||||
x:Class="Млаумчерб.Клиент.видимое.DownloadTaskView"
|
|
||||||
Padding="4" MaxHeight="60" MinWidth="200"
|
|
||||||
VerticalAlignment="Top"
|
|
||||||
HorizontalAlignment="Stretch"
|
|
||||||
BorderThickness="1" BorderBrush="#999999">
|
|
||||||
<Grid RowDefinitions="30 30" ColumnDefinitions="* 30">
|
|
||||||
<TextBlock Grid.Row="0" Grid.Column="0" Name="NameText"/>
|
|
||||||
<Button Grid.Row="0" Grid.Column="1"
|
|
||||||
Classes="button_no_border"
|
|
||||||
Background="Transparent"
|
|
||||||
Foreground="#FF4040"
|
|
||||||
FontSize="12"
|
|
||||||
Click="RemoveFromList">
|
|
||||||
[X]
|
|
||||||
</Button>
|
|
||||||
<TextBlock Grid.Row="1" Grid.Column="0" Name="DownloadedProgressText"/>
|
|
||||||
</Grid>
|
|
||||||
</UserControl>
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
using Avalonia.Controls;
|
|
||||||
using Avalonia.Interactivity;
|
|
||||||
using Avalonia.Threading;
|
|
||||||
using Млаумчерб.Клиент.сеть;
|
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент.видимое;
|
|
||||||
|
|
||||||
public partial class DownloadTaskView : UserControl
|
|
||||||
{
|
|
||||||
private readonly NetworkTask _task;
|
|
||||||
private readonly Action<DownloadTaskView> _removeFromList;
|
|
||||||
|
|
||||||
|
|
||||||
public DownloadTaskView()
|
|
||||||
{
|
|
||||||
throw new NotImplementedException();
|
|
||||||
}
|
|
||||||
|
|
||||||
public DownloadTaskView(NetworkTask task, Action<DownloadTaskView> removeFromList)
|
|
||||||
{
|
|
||||||
_task = task;
|
|
||||||
_removeFromList = removeFromList;
|
|
||||||
InitializeComponent();
|
|
||||||
NameText.Text = task.Name;
|
|
||||||
task.OnProgress += ReportProgress;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
void ReportProgress(DownloadProgress progress)
|
|
||||||
{
|
|
||||||
Dispatcher.UIThread.Invoke(() =>
|
|
||||||
{
|
|
||||||
DownloadedProgressText.Text = progress.ToString();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private void RemoveFromList(object? sender, RoutedEventArgs e)
|
|
||||||
{
|
|
||||||
_task.Cancel();
|
|
||||||
Dispatcher.UIThread.Invoke(() => _removeFromList.Invoke(this));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
using Avalonia.Controls;
|
|
||||||
using Avalonia.Media;
|
|
||||||
using Млаумчерб.Клиент.классы;
|
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент.видимое;
|
|
||||||
|
|
||||||
public partial class VersionItemView : ListBoxItem
|
|
||||||
{
|
|
||||||
public GameVersionProps Props { get; }
|
|
||||||
private SolidColorBrush _avaliableColor = new(Color.FromRgb(30, 130, 40));
|
|
||||||
private SolidColorBrush _unavaliableColor = new(Color.FromRgb(170, 70, 70));
|
|
||||||
|
|
||||||
public VersionItemView()
|
|
||||||
{
|
|
||||||
throw new NotImplementedException();
|
|
||||||
}
|
|
||||||
|
|
||||||
public VersionItemView(GameVersionProps props)
|
|
||||||
{
|
|
||||||
Props = props;
|
|
||||||
InitializeComponent();
|
|
||||||
text.Text = props.Name;
|
|
||||||
props.OnDownloadCompleted += UpdateBackground;
|
|
||||||
UpdateBackground();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void UpdateBackground()
|
|
||||||
{
|
|
||||||
Background = Props.IsDownloaded ? _avaliableColor : _unavaliableColor;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,122 +0,0 @@
|
|||||||
<Window xmlns="https://github.com/avaloniaui"
|
|
||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
|
||||||
xmlns:gif="clr-namespace:Avalonia.Labs.Gif;assembly=Avalonia.Labs.Gif"
|
|
||||||
xmlns:local="clr-namespace:Млаумчерб"
|
|
||||||
x:Class="Млаумчерб.Клиент.видимое.Окне"
|
|
||||||
Name="window"
|
|
||||||
Title="млаумчерб"
|
|
||||||
Icon="avares://млаумчерб/капитал/кубе.ico"
|
|
||||||
FontFamily="{StaticResource MonospaceFont}" FontSize="18"
|
|
||||||
MinWidth="800" MinHeight="500"
|
|
||||||
Width="800" Height="500"
|
|
||||||
WindowStartupLocation="CenterScreen">
|
|
||||||
<Grid>
|
|
||||||
<Grid.RowDefinitions>* 30</Grid.RowDefinitions>
|
|
||||||
<Image Grid.RowSpan="2" Stretch="UniformToFill"
|
|
||||||
Source="avares://млаумчерб/капитал/фоне.png"/>
|
|
||||||
|
|
||||||
<Grid Grid.Row="0" Margin="10">
|
|
||||||
<Grid.ColumnDefinitions>* 300 *</Grid.ColumnDefinitions>
|
|
||||||
<Border Grid.Column="0"
|
|
||||||
Classes="dark_tr_bg white_border">
|
|
||||||
<Grid>
|
|
||||||
<Grid.RowDefinitions>30 *</Grid.RowDefinitions>
|
|
||||||
<Border Classes="white_border" Margin="-1" Padding="4">
|
|
||||||
<TextBlock FontWeight="Bold"
|
|
||||||
HorizontalAlignment="Center"
|
|
||||||
VerticalAlignment="Center">
|
|
||||||
Лог
|
|
||||||
</TextBlock>
|
|
||||||
</Border>
|
|
||||||
<ScrollViewer Name="LogScrollViewer" Grid.Row="1"
|
|
||||||
HorizontalScrollBarVisibility="Disabled"
|
|
||||||
VerticalScrollBarVisibility="Visible"
|
|
||||||
Background="Transparent">
|
|
||||||
<TextBox Name="LogTextBox"
|
|
||||||
FontSize="14"
|
|
||||||
IsReadOnly="True" TextWrapping="Wrap"
|
|
||||||
VerticalAlignment="Top"
|
|
||||||
Background="Transparent" BorderThickness="0"/>
|
|
||||||
</ScrollViewer>
|
|
||||||
</Grid>
|
|
||||||
</Border>
|
|
||||||
<Border Grid.Column="1"
|
|
||||||
Classes="dark_tr_bg white_border"
|
|
||||||
Margin="10 0">
|
|
||||||
<Grid>
|
|
||||||
<Grid.RowDefinitions>* 60</Grid.RowDefinitions>
|
|
||||||
<StackPanel Orientation="Vertical" Margin="10" Spacing="10">
|
|
||||||
<TextBlock>Версия:</TextBlock>
|
|
||||||
<ComboBox Name="VersionComboBox"/>
|
|
||||||
|
|
||||||
<TextBlock>Ник:</TextBlock>
|
|
||||||
<TextBox Background="Transparent"
|
|
||||||
Text="{Binding #window.Username}"/>
|
|
||||||
|
|
||||||
<TextBlock>
|
|
||||||
<Run>Выделенная память:</Run>
|
|
||||||
<TextBox Background="Transparent" Padding="0"
|
|
||||||
BorderThickness="1"
|
|
||||||
BorderBrush="#777777"
|
|
||||||
Text="{Binding #window.MemoryLimit}">
|
|
||||||
</TextBox>
|
|
||||||
<Run>Мб</Run>
|
|
||||||
</TextBlock>
|
|
||||||
<Slider Minimum="2048" Maximum="8192"
|
|
||||||
Value="{Binding #window.MemoryLimit}">
|
|
||||||
</Slider>
|
|
||||||
|
|
||||||
<CheckBox IsChecked="{Binding #window.Fullscreen}">
|
|
||||||
Запустить полноэкранное
|
|
||||||
</CheckBox>
|
|
||||||
|
|
||||||
<CheckBox IsChecked="{Binding #window.CheckGameFiles}">
|
|
||||||
Проверить файлы игры
|
|
||||||
</CheckBox>
|
|
||||||
</StackPanel>
|
|
||||||
<Button Grid.Row="1" Margin="10" Padding="0 0 0 4"
|
|
||||||
Classes="button_no_border"
|
|
||||||
Background="#BBfd7300"
|
|
||||||
Click="Запуск">
|
|
||||||
Запуск
|
|
||||||
</Button>
|
|
||||||
</Grid>
|
|
||||||
</Border>
|
|
||||||
|
|
||||||
<Border Grid.Column="2" Classes="dark_tr_bg white_border">
|
|
||||||
<Grid>
|
|
||||||
<Grid.RowDefinitions>30 *</Grid.RowDefinitions>
|
|
||||||
<Border Classes="white_border" Margin="-1" Padding="4">
|
|
||||||
<TextBlock FontWeight="Bold"
|
|
||||||
HorizontalAlignment="Center"
|
|
||||||
VerticalAlignment="Center">
|
|
||||||
Загрузки
|
|
||||||
</TextBlock>
|
|
||||||
</Border>
|
|
||||||
<ScrollViewer Grid.Row="1"
|
|
||||||
HorizontalScrollBarVisibility="Disabled"
|
|
||||||
VerticalScrollBarVisibility="Visible"
|
|
||||||
Background="Transparent"
|
|
||||||
Padding="1">
|
|
||||||
<StackPanel Name="DownloadsPanel" VerticalAlignment="Top"/>
|
|
||||||
</ScrollViewer>
|
|
||||||
</Grid>
|
|
||||||
</Border>
|
|
||||||
</Grid>
|
|
||||||
<Border Grid.Row="1" Background="#954808B0">
|
|
||||||
<Grid>
|
|
||||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
|
|
||||||
<Button Classes="menu_button button_no_border" Click="ОткрытьПапкуЛаунчера">директория лаунчера</Button>
|
|
||||||
<Border Classes="menu_separator"/>
|
|
||||||
<Button Classes="menu_button button_no_border" Click="ОткрытьФайлЛогов">лог-файл</Button>
|
|
||||||
</StackPanel>
|
|
||||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
|
|
||||||
<Button Classes="menu_button button_no_border" Click="ОткрытьРепозиторий">исходный код</Button>
|
|
||||||
<gif:GifImage
|
|
||||||
Width="30" Height="30" Stretch="Uniform"
|
|
||||||
Source="avares://млаумчерб/капитал/лисик.gif"/>
|
|
||||||
</StackPanel>
|
|
||||||
</Grid>
|
|
||||||
</Border>
|
|
||||||
</Grid>
|
|
||||||
</Window>
|
|
||||||
@@ -1,179 +0,0 @@
|
|||||||
using Avalonia;
|
|
||||||
using Avalonia.Controls;
|
|
||||||
using Avalonia.Data;
|
|
||||||
using Avalonia.Interactivity;
|
|
||||||
using Avalonia.Platform.Storage;
|
|
||||||
using Avalonia.Threading;
|
|
||||||
using Млаумчерб.Клиент.классы;
|
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент.видимое;
|
|
||||||
|
|
||||||
public partial class Окне : Window
|
|
||||||
{
|
|
||||||
public static readonly StyledProperty<string> UsernameProperty =
|
|
||||||
AvaloniaProperty.Register<Окне, string>(nameof(Username),
|
|
||||||
defaultBindingMode: BindingMode.TwoWay);
|
|
||||||
public string Username
|
|
||||||
{
|
|
||||||
get => GetValue(UsernameProperty);
|
|
||||||
set => SetValue(UsernameProperty, value);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static readonly StyledProperty<int> MemoryLimitProperty =
|
|
||||||
AvaloniaProperty.Register<Окне, int>(nameof(MemoryLimit),
|
|
||||||
defaultBindingMode: BindingMode.TwoWay, defaultValue: 2048);
|
|
||||||
public int MemoryLimit
|
|
||||||
{
|
|
||||||
get => GetValue(MemoryLimitProperty);
|
|
||||||
set => SetValue(MemoryLimitProperty, value);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static readonly StyledProperty<bool> FullscreenProperty =
|
|
||||||
AvaloniaProperty.Register<Окне, bool>(nameof(Fullscreen),
|
|
||||||
defaultBindingMode: BindingMode.TwoWay, defaultValue: false);
|
|
||||||
public bool Fullscreen
|
|
||||||
{
|
|
||||||
get => GetValue(FullscreenProperty);
|
|
||||||
set => SetValue(FullscreenProperty, value);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static readonly StyledProperty<bool> CheckGameFilesProperty =
|
|
||||||
AvaloniaProperty.Register<Окне, bool>(nameof(CheckGameFiles),
|
|
||||||
defaultBindingMode: BindingMode.TwoWay, defaultValue: false);
|
|
||||||
public bool CheckGameFiles
|
|
||||||
{
|
|
||||||
get => GetValue(CheckGameFilesProperty);
|
|
||||||
set => SetValue(CheckGameFilesProperty, value);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Окне()
|
|
||||||
{
|
|
||||||
InitializeComponent();
|
|
||||||
}
|
|
||||||
|
|
||||||
protected override async void OnLoaded(RoutedEventArgs e)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
Приложение.Логгер.OnLogMessage += (context, severity, message, format) =>
|
|
||||||
{
|
|
||||||
if(severity == LogSeverity.Debug)
|
|
||||||
return;
|
|
||||||
|
|
||||||
StringBuilder b = new();
|
|
||||||
b.Append(DateTime.Now.ToString("[HH:mm:ss]["));
|
|
||||||
b.Append(severity);
|
|
||||||
b.Append("]: ");
|
|
||||||
b.Append(message);
|
|
||||||
b.Append('\n');
|
|
||||||
Dispatcher.UIThread.Invoke(() =>
|
|
||||||
{
|
|
||||||
double offsetFromBottom = LogScrollViewer.Extent.Height
|
|
||||||
- LogScrollViewer.Offset.Y
|
|
||||||
- LogScrollViewer.Viewport.Height;
|
|
||||||
bool is_scrolled_to_end = offsetFromBottom < 20.0; // scrolled less then one line up
|
|
||||||
LogTextBox.Text += b.ToString();
|
|
||||||
if (is_scrolled_to_end)
|
|
||||||
LogScrollViewer.ScrollToEnd();
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
Username = Приложение.Настройки.имя_пользователя;
|
|
||||||
MemoryLimit = Приложение.Настройки.выделенная_память_мб;
|
|
||||||
Fullscreen = Приложение.Настройки.открывать_на_весь_экран;
|
|
||||||
|
|
||||||
Directory.Create(Пути.GetVersionDescriptorDir());
|
|
||||||
VersionComboBox.SelectedIndex = 0;
|
|
||||||
VersionComboBox.IsEnabled = false;
|
|
||||||
var versions = await GameVersion.GetAllVersionsAsync();
|
|
||||||
Dispatcher.UIThread.Invoke(() =>
|
|
||||||
{
|
|
||||||
foreach (var p in versions)
|
|
||||||
{
|
|
||||||
VersionComboBox.Items.Add(new VersionItemView(p));
|
|
||||||
if (Приложение.Настройки.последняя_запущенная_версия != null &&
|
|
||||||
p.Name == Приложение.Настройки.последняя_запущенная_версия)
|
|
||||||
VersionComboBox.SelectedIndex = VersionComboBox.Items.Count - 1;
|
|
||||||
}
|
|
||||||
VersionComboBox.IsEnabled = true;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Ошибки.ПоказатьСообщение(nameof(Окне), ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async void Запуск(object? sender, RoutedEventArgs e)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var selectedVersionView = (VersionItemView?)VersionComboBox.SelectedItem;
|
|
||||||
var selectedVersion = selectedVersionView?.Props;
|
|
||||||
Приложение.Настройки.последняя_запущенная_версия = selectedVersion?.Name;
|
|
||||||
Приложение.Настройки.имя_пользователя = Username;
|
|
||||||
Приложение.Настройки.выделенная_память_мб = MemoryLimit;
|
|
||||||
Приложение.Настройки.открывать_на_весь_экран = Fullscreen;
|
|
||||||
Приложение.Настройки.СохранитьВФайл();
|
|
||||||
if (selectedVersion == null)
|
|
||||||
return;
|
|
||||||
|
|
||||||
var v = await GameVersion.CreateFromPropsAsync(selectedVersion);
|
|
||||||
var updateTasks = await v.CreateUpdateTasksAsync(CheckGameFiles);
|
|
||||||
foreach (var t in updateTasks)
|
|
||||||
{
|
|
||||||
var updateTask = t.StartAsync();
|
|
||||||
Dispatcher.UIThread.Invoke(() =>
|
|
||||||
{
|
|
||||||
var view = new DownloadTaskView(t, view => DownloadsPanel.Children.Remove(view));
|
|
||||||
DownloadsPanel.Children.Add(view);
|
|
||||||
});
|
|
||||||
await updateTask;
|
|
||||||
}
|
|
||||||
Dispatcher.UIThread.Invoke(() => CheckGameFiles = false);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Ошибки.ПоказатьСообщение(nameof(Окне), ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ОткрытьПапкуЛаунчера(object? s, RoutedEventArgs e)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
Launcher.LaunchDirectoryInfoAsync(new DirectoryInfo(Directory.GetCurrent().ToString()))
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Ошибки.ПоказатьСообщение(nameof(Окне), ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ОткрытьФайлЛогов(object? sender, RoutedEventArgs e)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
Launcher.LaunchFileInfoAsync(new FileInfo(Приложение.Логгер.LogfileName.ToString()))
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Ошибки.ПоказатьСообщение(nameof(Окне), ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ОткрытьРепозиторий(object? sender, RoutedEventArgs e)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
Launcher.LaunchUriAsync(new Uri("https://timerix.ddns.net:3322/Timerix/mlaumcherb"))
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Ошибки.ПоказатьСообщение(nameof(Окне), ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
using Avalonia;
|
|
||||||
using Avalonia.Controls.ApplicationLifetimes;
|
|
||||||
using Avalonia.Markup.Xaml;
|
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент.видимое;
|
|
||||||
|
|
||||||
public class Приложение : Application
|
|
||||||
{
|
|
||||||
public static LauncherLogger Логгер = new();
|
|
||||||
public static Настройки Настройки = new();
|
|
||||||
|
|
||||||
public override void Initialize()
|
|
||||||
{
|
|
||||||
Логгер.LogInfo(nameof(Приложение), "приложение запущено");
|
|
||||||
Настройки = Настройки.ЗагрузитьИзФайла();
|
|
||||||
AvaloniaXamlLoader.Load(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
public override void OnFrameworkInitializationCompleted()
|
|
||||||
{
|
|
||||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
|
||||||
{
|
|
||||||
desktop.MainWindow = new Окне();
|
|
||||||
}
|
|
||||||
|
|
||||||
base.OnFrameworkInitializationCompleted();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
namespace Млаумчерб.Клиент.классы;
|
|
||||||
|
|
||||||
public class ArgumentsWithPlaceholders
|
|
||||||
{
|
|
||||||
protected List<string> raw_args = new();
|
|
||||||
|
|
||||||
public List<string> FillPlaceholders(Dictionary<string, string> values)
|
|
||||||
{
|
|
||||||
List<string> result = new();
|
|
||||||
foreach (var a in raw_args)
|
|
||||||
{
|
|
||||||
var f = a;
|
|
||||||
int begin = a.IndexOf('$');
|
|
||||||
if (begin != -1)
|
|
||||||
{
|
|
||||||
int keyBegin = begin + 2;
|
|
||||||
int end = a.IndexOf('}', keyBegin);
|
|
||||||
if (end != -1)
|
|
||||||
{
|
|
||||||
var key = a.Substring(keyBegin, end - keyBegin);
|
|
||||||
if (!values.TryGetValue(key, out var v))
|
|
||||||
throw new Exception($"can't find value for placeholder '{key}'");
|
|
||||||
f = v;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
result.Add(f);
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
using DTLib.Extensions;
|
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент.классы;
|
|
||||||
|
|
||||||
public class GameArguments : ArgumentsWithPlaceholders
|
|
||||||
{
|
|
||||||
private static readonly string[] _enabled_features =
|
|
||||||
[
|
|
||||||
"has_custom_resolution"
|
|
||||||
];
|
|
||||||
|
|
||||||
public GameArguments(GameVersionDescriptor d)
|
|
||||||
{
|
|
||||||
if (d.minecraftArguments is not null)
|
|
||||||
{
|
|
||||||
raw_args.AddRange(d.minecraftArguments.SplitToList(' ', quot: '"'));
|
|
||||||
}
|
|
||||||
else if (d.arguments is not null)
|
|
||||||
{
|
|
||||||
foreach (var av in d.arguments.game)
|
|
||||||
{
|
|
||||||
if(Буржуазия.CheckRules(av.rules, _enabled_features))
|
|
||||||
raw_args.AddRange(av.value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
namespace Млаумчерб.Клиент.классы;
|
|
||||||
|
|
||||||
public class GameVersionCatalog
|
|
||||||
{
|
|
||||||
[JsonRequired] public List<RemoteVersionDescriptorProps> versions { get; set; } = null!;
|
|
||||||
}
|
|
||||||
|
|
||||||
public class AssetProperties
|
|
||||||
{
|
|
||||||
[JsonRequired] public string hash { get; set; } = "";
|
|
||||||
[JsonRequired] public int size { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public class AssetIndex
|
|
||||||
{
|
|
||||||
[JsonRequired] public Dictionary<string, AssetProperties> objects { get; set; } = new();
|
|
||||||
}
|
|
||||||
|
|
||||||
public class RemoteVersionDescriptorProps
|
|
||||||
{
|
|
||||||
[JsonRequired] public string id { get; set; } = "";
|
|
||||||
[JsonRequired] public string type { get; set; } = "";
|
|
||||||
[JsonRequired] public string url { get; set; } = "";
|
|
||||||
[JsonRequired] public string sha1 { get; set; } = "";
|
|
||||||
[JsonRequired] public DateTime time { get; set; }
|
|
||||||
[JsonRequired] public DateTime releaseTime { get; set; }
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
namespace Млаумчерб.Клиент.классы;
|
|
||||||
|
|
||||||
public class GameVersionProps
|
|
||||||
{
|
|
||||||
public string Name { get; }
|
|
||||||
public IOPath LocalDescriptorPath { get; }
|
|
||||||
public string? RemoteDescriptorUrl { get; }
|
|
||||||
private bool _isDownloaded;
|
|
||||||
public bool IsDownloaded
|
|
||||||
{
|
|
||||||
get => _isDownloaded;
|
|
||||||
set
|
|
||||||
{
|
|
||||||
bool downloadCompleted = value && !_isDownloaded;
|
|
||||||
_isDownloaded = value;
|
|
||||||
if(downloadCompleted)
|
|
||||||
OnDownloadCompleted?.Invoke();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
public event Action? OnDownloadCompleted;
|
|
||||||
|
|
||||||
public GameVersionProps(string name, string? url, IOPath descriptorPath)
|
|
||||||
{
|
|
||||||
Name = name;
|
|
||||||
LocalDescriptorPath = descriptorPath;
|
|
||||||
RemoteDescriptorUrl = url;
|
|
||||||
IsDownloaded = File.Exists(Пути.GetVersionJarFilePath(name));
|
|
||||||
}
|
|
||||||
|
|
||||||
public GameVersionProps(string name, string? url) :
|
|
||||||
this(name, url, Пути.GetVersionDescriptorPath(name)) { }
|
|
||||||
|
|
||||||
public override string ToString() => Name;
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
namespace Млаумчерб.Клиент.классы;
|
|
||||||
|
|
||||||
public class JavaArguments : ArgumentsWithPlaceholders
|
|
||||||
{
|
|
||||||
private static readonly string[] _initial_arguments =
|
|
||||||
[
|
|
||||||
|
|
||||||
];
|
|
||||||
|
|
||||||
private static readonly string[] _enabled_features =
|
|
||||||
[
|
|
||||||
|
|
||||||
];
|
|
||||||
|
|
||||||
public JavaArguments(GameVersionDescriptor d)
|
|
||||||
{
|
|
||||||
raw_args.AddRange(_initial_arguments);
|
|
||||||
if (d.arguments is not null)
|
|
||||||
{
|
|
||||||
foreach (var av in d.arguments.jvm)
|
|
||||||
{
|
|
||||||
if(Буржуазия.CheckRules(av.rules, _enabled_features))
|
|
||||||
raw_args.AddRange(av.value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
namespace Млаумчерб.Клиент.классы;
|
|
||||||
|
|
||||||
public class JavaVersionCatalog
|
|
||||||
{
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public class JavaVersionProps
|
|
||||||
{
|
|
||||||
[JsonRequired] public Artifact manifest { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public class JavaVersionManifest
|
|
||||||
{
|
|
||||||
[JsonRequired] public Dictionary<string, JavaDistributiveElementProps> manifest { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public class JavaDistributiveElementProps
|
|
||||||
{
|
|
||||||
// "directory" / "file"
|
|
||||||
[JsonRequired] public string type { get; set; } = "";
|
|
||||||
public bool? executable { get; set; }
|
|
||||||
public JavaCompressedArtifact? downloads { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public class JavaCompressedArtifact
|
|
||||||
{
|
|
||||||
public Artifact? lzma { get; set; }
|
|
||||||
public Artifact raw { get; set; } = null!;
|
|
||||||
}
|
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
using DTLib.Extensions;
|
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент.классы;
|
|
||||||
|
|
||||||
public class Libraries
|
|
||||||
{
|
|
||||||
private static readonly string[] enabled_features = [];
|
|
||||||
|
|
||||||
public record JarLib(string name, IOPath jarFilePath, Artifact artifact);
|
|
||||||
public record NativeLib(string name, IOPath jarFilePath, Artifact artifact, Extract? extractionOptions)
|
|
||||||
: JarLib(name, jarFilePath, artifact);
|
|
||||||
|
|
||||||
public IReadOnlyCollection<JarLib> Libs { get; }
|
|
||||||
|
|
||||||
public Libraries(GameVersionDescriptor descriptor)
|
|
||||||
{
|
|
||||||
List<JarLib> libs = new();
|
|
||||||
HashSet<string> libHashes = new();
|
|
||||||
|
|
||||||
foreach (var l in descriptor.libraries)
|
|
||||||
{
|
|
||||||
if (l.rules != null && !Буржуазия.CheckRules(l.rules, enabled_features))
|
|
||||||
continue;
|
|
||||||
|
|
||||||
if (l.natives != null)
|
|
||||||
{
|
|
||||||
string? nativesKey;
|
|
||||||
if (OperatingSystem.IsWindows())
|
|
||||||
nativesKey = l.natives.windows;
|
|
||||||
else if (OperatingSystem.IsLinux())
|
|
||||||
nativesKey = l.natives.linux;
|
|
||||||
else if (OperatingSystem.IsMacOS())
|
|
||||||
nativesKey = l.natives.osx;
|
|
||||||
else throw new PlatformNotSupportedException();
|
|
||||||
if(nativesKey is null)
|
|
||||||
throw new Exception($"nativesKey for '{l.name}' is null");
|
|
||||||
|
|
||||||
Artifact artifact = null!;
|
|
||||||
if(l.downloads.classifiers != null && !l.downloads.classifiers.TryGetValue(nativesKey, out artifact!))
|
|
||||||
throw new Exception($"can't find artifact for '{l.name}' with nativesKey '{nativesKey}'");
|
|
||||||
|
|
||||||
// skipping duplicates (WHO THE HELL CREATES THIS DISCRIPTORS AAAAAAAAA)
|
|
||||||
if(!libHashes.Add(artifact.sha1))
|
|
||||||
continue;
|
|
||||||
|
|
||||||
string urlTail = artifact.url.AsSpan().After("://").After('/').ToString();
|
|
||||||
IOPath jarFilePath = Path.Concat(Пути.GetLibrariesDir(), urlTail);
|
|
||||||
libs.Add(new NativeLib(l.name, jarFilePath, artifact, l.extract));
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
Artifact? artifact = l.downloads.artifact;
|
|
||||||
if (artifact == null)
|
|
||||||
throw new NullReferenceException($"artifact for '{l.name}' is null");
|
|
||||||
|
|
||||||
// skipping duplicates
|
|
||||||
if(!libHashes.Add(artifact.sha1))
|
|
||||||
continue;
|
|
||||||
|
|
||||||
string urlTail = artifact.url.AsSpan().After("://").After('/').ToString();
|
|
||||||
IOPath jarFilePath = Path.Concat(Пути.GetLibrariesDir(), urlTail);
|
|
||||||
libs.Add(new JarLib(l.name, jarFilePath, artifact));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Libs = libs;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
using System.Runtime.InteropServices;
|
|
||||||
// ReSharper disable CollectionNeverUpdated.Global
|
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент.классы;
|
|
||||||
|
|
||||||
public static class Буржуазия
|
|
||||||
{
|
|
||||||
public static bool CheckOs(Os os) =>
|
|
||||||
os.name switch
|
|
||||||
{
|
|
||||||
null => true,
|
|
||||||
"osx" => OperatingSystem.IsMacOS(),
|
|
||||||
"linux" => OperatingSystem.IsLinux(),
|
|
||||||
"windows" => OperatingSystem.IsWindows(),
|
|
||||||
_ => throw new ArgumentOutOfRangeException(os.name)
|
|
||||||
}
|
|
||||||
&& os.arch switch
|
|
||||||
{
|
|
||||||
null => true,
|
|
||||||
"x86" => RuntimeInformation.OSArchitecture == Architecture.X86,
|
|
||||||
"x64" => RuntimeInformation.OSArchitecture == Architecture.X64,
|
|
||||||
"arm64" => RuntimeInformation.OSArchitecture == Architecture.Arm64,
|
|
||||||
_ => false
|
|
||||||
};
|
|
||||||
|
|
||||||
public static bool CheckRules(ICollection<Rule> rules, ICollection<string> enabled_features)
|
|
||||||
{
|
|
||||||
bool allowed = false;
|
|
||||||
foreach (var r in rules)
|
|
||||||
{
|
|
||||||
if (r.os == null || CheckOs(r.os))
|
|
||||||
{
|
|
||||||
if (r.features != null)
|
|
||||||
{
|
|
||||||
foreach (var feature in enabled_features)
|
|
||||||
{
|
|
||||||
if(r.features.TryGetValue(feature, out bool is_enabled))
|
|
||||||
{
|
|
||||||
if (is_enabled)
|
|
||||||
{
|
|
||||||
if (r.action != "allow")
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (r.action == "allow")
|
|
||||||
allowed = true;
|
|
||||||
else return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return allowed;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static string GetOs() =>
|
|
||||||
Environment.OSVersion.Platform switch
|
|
||||||
{
|
|
||||||
PlatformID.Win32NT => "windows",
|
|
||||||
PlatformID.Unix => "linux",
|
|
||||||
PlatformID.MacOSX => "osx",
|
|
||||||
_ => throw new ArgumentOutOfRangeException(Environment.OSVersion.Platform.ToString())
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
namespace Млаумчерб.Клиент.классы;
|
|
||||||
|
|
||||||
public static class Пролетариат
|
|
||||||
{
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
using Млаумчерб.Клиент.видимое;
|
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент.классы;
|
|
||||||
|
|
||||||
public static class Пути
|
|
||||||
{
|
|
||||||
public static IOPath GetAssetIndexFilePath(string id) =>
|
|
||||||
Path.Concat(Приложение.Настройки.путь_к_кубачу, $"assets/indexes/{id}.json");
|
|
||||||
|
|
||||||
public static IOPath GetVersionDescriptorDir() =>
|
|
||||||
Path.Concat(Приложение.Настройки.путь_к_кубачу, "version_descriptors");
|
|
||||||
|
|
||||||
public static string GetVersionDescriptorName(IOPath path) =>
|
|
||||||
path.LastName().RemoveExtension().ToString();
|
|
||||||
|
|
||||||
public static IOPath GetVersionDescriptorPath(string name) =>
|
|
||||||
Path.Concat(GetVersionDescriptorDir(), Path.ReplaceRestrictedChars(name) + ".json");
|
|
||||||
|
|
||||||
public static IOPath GetVersionDir(string id) =>
|
|
||||||
Path.Concat(Приложение.Настройки.путь_к_кубачу, "versions", id);
|
|
||||||
|
|
||||||
public static IOPath GetVersionJarFilePath(string id) =>
|
|
||||||
Path.Concat(GetVersionDir(id), id + ".jar");
|
|
||||||
|
|
||||||
public static IOPath GetLibrariesDir() =>
|
|
||||||
Path.Concat(Приложение.Настройки.путь_к_кубачу, "libraries");
|
|
||||||
|
|
||||||
public static IOPath GetNativeLibrariesDir(string id) =>
|
|
||||||
Path.Concat(GetVersionDir(id), "natives", Буржуазия.GetOs());
|
|
||||||
|
|
||||||
public static IOPath GetJavaRuntimesDir() =>
|
|
||||||
Path.Concat(Приложение.Настройки.путь_к_кубачу, "java");
|
|
||||||
|
|
||||||
|
|
||||||
public static IOPath GetJavaRuntimeDir(string id) =>
|
|
||||||
Path.Concat(GetJavaRuntimesDir(), id);
|
|
||||||
|
|
||||||
public static IOPath GetJavaExecutablePath(string id) =>
|
|
||||||
Path.Concat(GetJavaRuntimeDir(id), "bin",
|
|
||||||
OperatingSystem.IsWindows() ? "javaw.exe" : "javaw");
|
|
||||||
}
|
|
||||||
@@ -1,112 +0,0 @@
|
|||||||
using System.Security.Cryptography;
|
|
||||||
using DTLib.Extensions;
|
|
||||||
using Млаумчерб.Клиент.видимое;
|
|
||||||
using Млаумчерб.Клиент.классы;
|
|
||||||
using static Млаумчерб.Клиент.сеть.Сеть;
|
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент.сеть.NetworkTaskFactories;
|
|
||||||
|
|
||||||
public class AssetsDownloadTaskFactory : INetworkTaskFactory
|
|
||||||
{
|
|
||||||
private const string ASSET_SERVER_URL = "https://resources.download.minecraft.net/";
|
|
||||||
private GameVersionDescriptor _descriptor;
|
|
||||||
private SHA1 _hasher;
|
|
||||||
private IOPath _indexFilePath;
|
|
||||||
List<AssetDownloadProperties> _assetsToDownload = new();
|
|
||||||
|
|
||||||
public AssetsDownloadTaskFactory(GameVersionDescriptor descriptor)
|
|
||||||
{
|
|
||||||
_descriptor = descriptor;
|
|
||||||
_hasher = SHA1.Create();
|
|
||||||
_indexFilePath = Пути.GetAssetIndexFilePath(_descriptor.assetIndex.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<NetworkTask?> CreateAsync(bool checkHashes)
|
|
||||||
{
|
|
||||||
if (!await CheckFilesAsync(checkHashes))
|
|
||||||
return new NetworkTask(
|
|
||||||
$"assets '{_descriptor.assetIndex.id}'",
|
|
||||||
GetTotalSize(),
|
|
||||||
Download
|
|
||||||
);
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
private async Task<bool> CheckFilesAsync(bool checkHashes)
|
|
||||||
{
|
|
||||||
if(!File.Exists(_indexFilePath))
|
|
||||||
{
|
|
||||||
Приложение.Логгер.LogInfo(nameof(Сеть), $"started downloading asset index to '{_indexFilePath}'");
|
|
||||||
await DownloadFileHTTP(_descriptor.assetIndex.url, _indexFilePath);
|
|
||||||
Приложение.Логгер.LogInfo(nameof(Сеть), "finished downloading asset index");
|
|
||||||
}
|
|
||||||
|
|
||||||
string indexFileText = File.ReadAllText(_indexFilePath);
|
|
||||||
var assetIndex = JsonConvert.DeserializeObject<AssetIndex>(indexFileText)
|
|
||||||
?? throw new Exception($"can't deserialize asset index file '{_indexFilePath}'");
|
|
||||||
|
|
||||||
_assetsToDownload.Clear();
|
|
||||||
// removing duplicates for Dictionary (idk how can it be possible, but Newtonsoft.Json creates them)
|
|
||||||
HashSet<string> assetHashes = new HashSet<string>();
|
|
||||||
foreach (var pair in assetIndex.objects)
|
|
||||||
{
|
|
||||||
if (assetHashes.Add(pair.Value.hash))
|
|
||||||
{
|
|
||||||
var a = new AssetDownloadProperties(pair.Key, pair.Value);
|
|
||||||
if (!File.Exists(a.filePath))
|
|
||||||
{
|
|
||||||
_assetsToDownload.Add(a);
|
|
||||||
}
|
|
||||||
else if(checkHashes)
|
|
||||||
{
|
|
||||||
await using var fs = File.OpenRead(a.filePath);
|
|
||||||
string hash = _hasher.ComputeHash(fs).HashToString();
|
|
||||||
if (hash != a.hash)
|
|
||||||
_assetsToDownload.Add(a);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return _assetsToDownload.Count == 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
private long GetTotalSize()
|
|
||||||
{
|
|
||||||
long totalSize = 0;
|
|
||||||
foreach (var a in _assetsToDownload)
|
|
||||||
totalSize += a.size;
|
|
||||||
return totalSize;
|
|
||||||
}
|
|
||||||
|
|
||||||
private class AssetDownloadProperties
|
|
||||||
{
|
|
||||||
public string name;
|
|
||||||
public string hash;
|
|
||||||
public long size;
|
|
||||||
public string url;
|
|
||||||
public IOPath filePath;
|
|
||||||
|
|
||||||
public AssetDownloadProperties(string key, GameAssetProperties p)
|
|
||||||
{
|
|
||||||
name = key;
|
|
||||||
hash = p.hash;
|
|
||||||
size = p.size;
|
|
||||||
string hashStart = hash.Substring(0, 2);
|
|
||||||
url = $"{ASSET_SERVER_URL}/{hashStart}/{hash}";
|
|
||||||
filePath = Path.Concat(IOPath.ArrayCast(["assets", "objects", hashStart, hash], true));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
|
|
||||||
{
|
|
||||||
Приложение.Логгер.LogInfo(nameof(Сеть), $"started downloading assets '{_descriptor.assetIndex.id}'");
|
|
||||||
ParallelOptions opt = new() { MaxDegreeOfParallelism = ParallelDownloadsN, CancellationToken = ct };
|
|
||||||
await Parallel.ForEachAsync(_assetsToDownload, opt,
|
|
||||||
async (a, _ct) =>
|
|
||||||
{
|
|
||||||
Приложение.Логгер.LogDebug(nameof(Сеть), $"downloading asset '{a.name}' {a.hash}");
|
|
||||||
await DownloadFileHTTP(a.url, a.filePath, _ct, pr.AddBytesCount);
|
|
||||||
});
|
|
||||||
Приложение.Логгер.LogInfo(nameof(Сеть), $"finished downloading assets '{_descriptor.assetIndex.id}'");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
using System.Security.Cryptography;
|
|
||||||
using EasyCompressor;
|
|
||||||
using Млаумчерб.Клиент.классы;
|
|
||||||
using static Млаумчерб.Клиент.сеть.Сеть;
|
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент.сеть.NetworkTaskFactories;
|
|
||||||
|
|
||||||
public class JavaDownloadTaskFactory : INetworkTaskFactory
|
|
||||||
{
|
|
||||||
private const string INDEX_URL =
|
|
||||||
"https://launchermeta.mojang.com/v1/products/java-runtime/2ec0cc96c44e5a76b9c8b7c39df7210883d12871/all.json";
|
|
||||||
private GameVersionDescriptor _descriptor;
|
|
||||||
private IOPath _javaVersionDir;
|
|
||||||
private SHA1 _hasher;
|
|
||||||
private LZMACompressor _lzma;
|
|
||||||
|
|
||||||
public JavaDownloadTaskFactory(GameVersionDescriptor descriptor)
|
|
||||||
{
|
|
||||||
_descriptor = descriptor;
|
|
||||||
_javaVersionDir = Пути.GetJavaRuntimeDir(_descriptor.javaVersion.component);
|
|
||||||
_hasher = SHA1.Create();
|
|
||||||
_lzma = new LZMACompressor();
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<NetworkTask?> CreateAsync(bool checkHashes)
|
|
||||||
{
|
|
||||||
NetworkTask? networkTask = null;
|
|
||||||
if (!CheckFiles(checkHashes))
|
|
||||||
networkTask = new(
|
|
||||||
$"java runtime '{_descriptor.javaVersion.component}'",
|
|
||||||
GetTotalSize(),
|
|
||||||
Download
|
|
||||||
);
|
|
||||||
return Task.FromResult(networkTask);
|
|
||||||
}
|
|
||||||
|
|
||||||
private bool CheckFiles(bool checkHashes)
|
|
||||||
{
|
|
||||||
//TODO: download catalog
|
|
||||||
//TODO: download manifest for required runtime
|
|
||||||
//TODO: check whether files from manifest exist and match hashes
|
|
||||||
throw new NotImplementedException();
|
|
||||||
}
|
|
||||||
|
|
||||||
private long GetTotalSize()
|
|
||||||
{
|
|
||||||
//TODO: sum up size of all files invalidated by CheckFiles
|
|
||||||
throw new NotImplementedException();
|
|
||||||
}
|
|
||||||
|
|
||||||
private Task Download(NetworkProgressReporter pr, CancellationToken ct)
|
|
||||||
{
|
|
||||||
//TODO: download files using lzma decompression
|
|
||||||
throw new NotImplementedException();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,101 +0,0 @@
|
|||||||
using System.IO.Compression;
|
|
||||||
using System.Security.Cryptography;
|
|
||||||
using DTLib.Extensions;
|
|
||||||
using Млаумчерб.Клиент.видимое;
|
|
||||||
using Млаумчерб.Клиент.классы;
|
|
||||||
using static Млаумчерб.Клиент.сеть.Сеть;
|
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент.сеть.NetworkTaskFactories;
|
|
||||||
|
|
||||||
public class LibrariesDownloadTaskFactory : INetworkTaskFactory
|
|
||||||
{
|
|
||||||
private GameVersionDescriptor _descriptor;
|
|
||||||
private Libraries _libraries;
|
|
||||||
private SHA1 _hasher;
|
|
||||||
private List<Libraries.JarLib> _libsToDownload = new();
|
|
||||||
private IOPath _nativesDir;
|
|
||||||
|
|
||||||
public LibrariesDownloadTaskFactory(GameVersionDescriptor descriptor, Libraries libraries)
|
|
||||||
{
|
|
||||||
_descriptor = descriptor;
|
|
||||||
_libraries = libraries;
|
|
||||||
_hasher = SHA1.Create();
|
|
||||||
_nativesDir = Пути.GetNativeLibrariesDir(descriptor.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<NetworkTask?> CreateAsync(bool checkHashes)
|
|
||||||
{
|
|
||||||
NetworkTask? networkTask = null;
|
|
||||||
if (!CheckFiles(checkHashes))
|
|
||||||
networkTask = new NetworkTask(
|
|
||||||
$"libraries '{_descriptor.id}'",
|
|
||||||
GetTotalSize(),
|
|
||||||
Download
|
|
||||||
);
|
|
||||||
return Task.FromResult(networkTask);
|
|
||||||
}
|
|
||||||
|
|
||||||
private bool CheckFiles(bool checkHashes)
|
|
||||||
{
|
|
||||||
_libsToDownload.Clear();
|
|
||||||
bool nativeDirExists = Directory.Exists(_nativesDir);
|
|
||||||
|
|
||||||
foreach (var l in _libraries.Libs)
|
|
||||||
{
|
|
||||||
if (!File.Exists(l.jarFilePath))
|
|
||||||
{
|
|
||||||
_libsToDownload.Add(l);
|
|
||||||
}
|
|
||||||
else if (!nativeDirExists && l is Libraries.NativeLib)
|
|
||||||
{
|
|
||||||
_libsToDownload.Add(l);
|
|
||||||
}
|
|
||||||
else if (checkHashes)
|
|
||||||
{
|
|
||||||
using var fs = File.OpenRead(l.jarFilePath);
|
|
||||||
string hash = _hasher.ComputeHash(fs).HashToString();
|
|
||||||
if(hash != l.artifact.sha1)
|
|
||||||
_libsToDownload.Add(l);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return _libsToDownload.Count == 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
private long GetTotalSize()
|
|
||||||
{
|
|
||||||
long total = 0;
|
|
||||||
foreach (var l in _libsToDownload)
|
|
||||||
total += l.artifact.size;
|
|
||||||
return total;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
|
|
||||||
{
|
|
||||||
Приложение.Логгер.LogInfo(nameof(Сеть), $"started downloading libraries '{_descriptor.id}'");
|
|
||||||
ParallelOptions opt = new() { MaxDegreeOfParallelism = ParallelDownloadsN, CancellationToken = ct };
|
|
||||||
await Parallel.ForEachAsync(_libsToDownload, opt, async (l, _ct) =>
|
|
||||||
{
|
|
||||||
Приложение.Логгер.LogDebug(nameof(Сеть),
|
|
||||||
$"downloading library '{l.name}' to '{l.jarFilePath}'");
|
|
||||||
await DownloadFileHTTP(l.artifact.url, l.jarFilePath, _ct, pr.AddBytesCount);
|
|
||||||
if (l is Libraries.NativeLib n)
|
|
||||||
{
|
|
||||||
var zipf = File.OpenRead(n.jarFilePath);
|
|
||||||
ZipFile.ExtractToDirectory(zipf, _nativesDir.ToString(), true);
|
|
||||||
if (n.extractionOptions?.exclude != null)
|
|
||||||
{
|
|
||||||
foreach (var excluded in n.extractionOptions.exclude)
|
|
||||||
{
|
|
||||||
IOPath path = Path.Concat(_nativesDir, excluded);
|
|
||||||
if(Directory.Exists(path))
|
|
||||||
Directory.Delete(path);
|
|
||||||
if(File.Exists(path))
|
|
||||||
File.Delete(path);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Приложение.Логгер.LogInfo(nameof(Сеть), $"finished downloading libraries '{_descriptor.id}'");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
using System.Security.Cryptography;
|
|
||||||
using DTLib.Extensions;
|
|
||||||
using Млаумчерб.Клиент.видимое;
|
|
||||||
using Млаумчерб.Клиент.классы;
|
|
||||||
using static Млаумчерб.Клиент.сеть.Сеть;
|
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент.сеть.NetworkTaskFactories;
|
|
||||||
|
|
||||||
public class VersionFileDownloadTaskFactory : INetworkTaskFactory
|
|
||||||
{
|
|
||||||
private GameVersionDescriptor _descriptor;
|
|
||||||
private IOPath _filePath;
|
|
||||||
private SHA1 _hasher;
|
|
||||||
|
|
||||||
public VersionFileDownloadTaskFactory(GameVersionDescriptor descriptor)
|
|
||||||
{
|
|
||||||
_descriptor = descriptor;
|
|
||||||
_filePath = Пути.GetVersionJarFilePath(_descriptor.id);
|
|
||||||
_hasher = SHA1.Create();
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<NetworkTask?> CreateAsync(bool checkHashes)
|
|
||||||
{
|
|
||||||
NetworkTask? networkTask = null;
|
|
||||||
if (!CheckFiles(checkHashes))
|
|
||||||
networkTask = new NetworkTask(
|
|
||||||
$"version file '{_descriptor.id}'",
|
|
||||||
GetTotalSize(),
|
|
||||||
Download
|
|
||||||
);
|
|
||||||
return Task.FromResult(networkTask);
|
|
||||||
}
|
|
||||||
|
|
||||||
private bool CheckFiles(bool checkHashes)
|
|
||||||
{
|
|
||||||
if (!File.Exists(_filePath))
|
|
||||||
return false;
|
|
||||||
if (!checkHashes)
|
|
||||||
return true;
|
|
||||||
using var fs = File.OpenRead(_filePath);
|
|
||||||
string hash = _hasher.ComputeHash(fs).HashToString();
|
|
||||||
return hash == _descriptor.downloads.client.sha1;
|
|
||||||
}
|
|
||||||
|
|
||||||
private long GetTotalSize()
|
|
||||||
{
|
|
||||||
return _descriptor.downloads.client.size;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
|
|
||||||
{
|
|
||||||
Приложение.Логгер.LogInfo(nameof(Сеть), $"started downloading version file '{_descriptor.id}'");
|
|
||||||
await DownloadFileHTTP(_descriptor.downloads.client.url, _filePath, ct, pr.AddBytesCount);
|
|
||||||
Приложение.Логгер.LogInfo(nameof(Сеть), $"finished downloading version file '{_descriptor.id}'");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
using System.Buffers;
|
|
||||||
using System.Net.Http;
|
|
||||||
using Млаумчерб.Клиент.видимое;
|
|
||||||
using Млаумчерб.Клиент.классы;
|
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент.сеть;
|
|
||||||
|
|
||||||
public static class Сеть
|
|
||||||
{
|
|
||||||
public static int ParallelDownloadsN = 32;
|
|
||||||
public static HttpClient http = new();
|
|
||||||
|
|
||||||
public static async Task DownloadFileHTTP(string url, IOPath outPath, CancellationToken ct = default,
|
|
||||||
Action<ArraySegment<byte>>? transformFunc = null)
|
|
||||||
{
|
|
||||||
await using var src = await http.GetStreamAsync(url, ct);
|
|
||||||
await using var dst = File.OpenWrite(outPath);
|
|
||||||
|
|
||||||
await src.CopyTransformAsync(dst, transformFunc, ct).ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static async Task CopyTransformAsync(this Stream src, Stream dst,
|
|
||||||
Action<ArraySegment<byte>>? transformFunc = null, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
// default dotnet runtime buffer size
|
|
||||||
int bufferSize = 81920;
|
|
||||||
byte[] readBuffer = ArrayPool<byte>.Shared.Rent(bufferSize);
|
|
||||||
byte[] writeBuffer = ArrayPool<byte>.Shared.Rent(bufferSize);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var readTask = src.ReadAsync(readBuffer, 0, bufferSize, ct).ConfigureAwait(false);
|
|
||||||
while (true)
|
|
||||||
{
|
|
||||||
int readCount = await readTask;
|
|
||||||
if (readCount == 0)
|
|
||||||
break;
|
|
||||||
(readBuffer, writeBuffer) = (writeBuffer, readBuffer);
|
|
||||||
readTask = src.ReadAsync(readBuffer, 0, bufferSize, ct).ConfigureAwait(false);
|
|
||||||
transformFunc?.Invoke(new ArraySegment<byte>(writeBuffer, 0, readCount));
|
|
||||||
dst.Write(writeBuffer, 0, readCount);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (OperationCanceledException)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
ArrayPool<byte>.Shared.Return(readBuffer);
|
|
||||||
ArrayPool<byte>.Shared.Return(writeBuffer);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static readonly string[] VERSION_MANIFEST_URLS =
|
|
||||||
{
|
|
||||||
"https://piston-meta.mojang.com/mc/game/version_manifest_v2.json"
|
|
||||||
};
|
|
||||||
|
|
||||||
private static async Task<List<RemoteVersionDescriptorProps>> GetRemoteVersionDescriptorsAsync()
|
|
||||||
{
|
|
||||||
List<RemoteVersionDescriptorProps> descriptors = new();
|
|
||||||
foreach (var url in VERSION_MANIFEST_URLS)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var manifestText = await http.GetStringAsync(url);
|
|
||||||
var catalog = JsonConvert.DeserializeObject<GameVersionCatalog>(manifestText);
|
|
||||||
if (catalog != null)
|
|
||||||
descriptors.AddRange(catalog.versions);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Приложение.Логгер.LogWarn(nameof(Сеть), ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return descriptors;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static List<GameVersionProps>? _versionPropsList;
|
|
||||||
|
|
||||||
/// <returns>empty list if couldn't find any remote versions</returns>
|
|
||||||
public static async Task<IReadOnlyList<GameVersionProps>> GetDownloadableVersions()
|
|
||||||
{
|
|
||||||
if (_versionPropsList == null)
|
|
||||||
{
|
|
||||||
_versionPropsList = new();
|
|
||||||
var rvdlist = await GetRemoteVersionDescriptorsAsync();
|
|
||||||
foreach (var r in rvdlist)
|
|
||||||
{
|
|
||||||
if (r.type == "release")
|
|
||||||
_versionPropsList.Add(new GameVersionProps(r.id, r.url));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return _versionPropsList;
|
|
||||||
}
|
|
||||||
}
|
|
||||||