Merge pull request #1605 from Jklawreszuk/launcher-refactor

[Launcher] Code refactor
This commit is contained in:
Marian Dziubiak 2023-02-11 18:48:09 +00:00 коммит произвёл GitHub
Родитель c6431b8b04 c89d04b8aa
Коммит 3e4d7aadb9
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
37 изменённых файлов: 375 добавлений и 419 удалений

Просмотреть файл

@ -46,7 +46,7 @@ namespace Stride.Core.Yaml
var input = new StringReader(assetAsString);
yamlStream = new YamlStream();
yamlStream.Load(input);
if (yamlStream.Documents.Count != 1 || !(yamlStream.Documents[0].RootNode is YamlMappingNode))
throw new YamlException("Unable to load the given stream");
}

Просмотреть файл

@ -2,7 +2,6 @@
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using Stride.Core.Yaml.Serialization;

Просмотреть файл

@ -7,6 +7,6 @@ namespace Stride.Core.Yaml
/// </summary>
public class DynamicYamlEmpty : DynamicYamlObject
{
public static readonly DynamicYamlEmpty Default = new DynamicYamlEmpty();
public static readonly DynamicYamlEmpty Default = new DynamicYamlEmpty();
}
}

Просмотреть файл

@ -263,7 +263,7 @@ namespace Stride.Core.Yaml
var newMemberName = type == OverrideType.Base
? key
: $"{key}{type.ToText()}";
keyMapping[key] = newMemberName;
overrides[key] = type;
@ -301,7 +301,7 @@ namespace Stride.Core.Yaml
keyMapping[key] = key;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return node.Children.Select(x => new KeyValuePair<dynamic, dynamic>(ConvertToDynamic(x.Key), ConvertToDynamic(x.Value))).ToArray().GetEnumerator();

Просмотреть файл

@ -1,6 +1,5 @@
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using System.Dynamic;
using System.Globalization;
using Stride.Core.Yaml.Serialization;

Просмотреть файл

@ -1,13 +1,10 @@
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using NuGet.ProjectModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Xml;
using Stride.Core;
using NuGet.ProjectModel;
using Stride.Core.Extensions;
using Stride.Core.VisualStudio;
@ -24,11 +21,11 @@ namespace Stride.Core.Assets
{
// Solution file: extract projects
var solutionDirectory = Path.GetDirectoryName(fullPath) ?? "";
var solution = Stride.Core.VisualStudio.Solution.FromFile(fullPath);
var solution = Solution.FromFile(fullPath);
foreach (var project in solution.Projects)
{
if (project.TypeGuid == VisualStudio.KnownProjectTypeGuid.CSharp || project.TypeGuid == VisualStudio.KnownProjectTypeGuid.CSharpNewSystem)
if (project.TypeGuid == KnownProjectTypeGuid.CSharp || project.TypeGuid == KnownProjectTypeGuid.CSharpNewSystem)
{
var projectPath = project.FullPath;
var projectAssetsJsonPath = Path.Combine(Path.GetDirectoryName(projectPath), @"obj", LockFileFormat.AssetsFileName);
@ -47,7 +44,7 @@ namespace Stride.Core.Assets
{
if ((library.Type == "package" || library.Type == "project") && (library.Name == "Stride.Engine" || library.Name == "Xenko.Engine"))
{
return new PackageVersion((string)library.Version.ToString());
return new PackageVersion(library.Version.ToString());
}
}
}
@ -74,15 +71,15 @@ namespace Stride.Core.Assets
if (project.IsSolutionFolder)
{
foreach (var solutionPackageIdentifier in SolutionPackageIdentifier)
if (project.Sections.Contains(solutionPackageIdentifier))
{
var propertyItem = project.Sections[solutionPackageIdentifier].Properties.FirstOrDefault();
if (propertyItem != null)
if (project.Sections.Contains(solutionPackageIdentifier))
{
packagePathRelative = propertyItem.Name;
return true;
var propertyItem = project.Sections[solutionPackageIdentifier].Properties.FirstOrDefault();
if (propertyItem != null)
{
packagePathRelative = propertyItem.Name;
return true;
}
}
}
}
return false;
}

Просмотреть файл

@ -1,9 +1,7 @@
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Stride.Core.Assets.Editor
{
@ -22,7 +20,7 @@ namespace Stride.Core.Assets.Editor
public static string EditorConfigPath => Path.Combine(UserDataPath, "GameStudioSettings.conf");
public static string InternalConfigPath => Path.Combine(UserDataPath, "GameStudioInternal.conf");
private static string ProductNameDirectory => "Stride";
}
}

Просмотреть файл

@ -3,7 +3,6 @@
using System;
using System.Diagnostics;
using Stride.Core;
using Stride.Core.Annotations;
using Stride.Core.IO;

Просмотреть файл

@ -7,8 +7,8 @@ using System.Linq;
using Stride.Core.Annotations;
using Stride.Core.Extensions;
using Stride.Core.IO;
using Stride.Core.Settings;
using Stride.Core.Presentation.Collections;
using Stride.Core.Settings;
namespace Stride.Core.MostRecentlyUsedFiles
{

Просмотреть файл

@ -24,7 +24,7 @@ namespace Stride.Editor.CrashReport
settings = storeCrashEmailSetting;
currentData = crashReport;
InitializeComponent();
textBoxLog.Text = crashReport.ToString();
textBoxLog.Text = crashReport.ToString();
if (settings == null)
{
emailCheckbox.Visible = false;
@ -82,7 +82,7 @@ namespace Stride.Editor.CrashReport
settings.Email = "";
settings.Save();
}
RefreshReport();
MailReport(currentData);

Просмотреть файл

@ -1,7 +1,6 @@
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using System.IO;
using System.Windows;
using Microsoft.Win32;

Просмотреть файл

@ -1,14 +1,11 @@
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using Stride.Core.Extensions;
using Stride.Core.Windows;
using Stride.LauncherApp.Views;
using Stride.CrashReport;
using Stride.Editor.CrashReport;
@ -31,7 +28,7 @@ namespace Stride.LauncherApp.CrashReport
var englishCulture = new CultureInfo("en-US");
var crashLogThread = new Thread(CrashReport) { CurrentUICulture = englishCulture, CurrentCulture = englishCulture };
crashLogThread.Start(new CrashReportArgs { Dispatcher = dispatcher, Exception = exception });
crashLogThread.Start(new CrashReportArgs(exception, dispatcher));
crashLogThread.Join();
}
@ -72,10 +69,6 @@ namespace Stride.LauncherApp.CrashReport
reporter.ShowDialog();
}
private class CrashReportArgs
{
public Exception Exception;
public Dispatcher Dispatcher;
}
private record CrashReportArgs(Exception Exception, Dispatcher Dispatcher);
}
}

Просмотреть файл

@ -1,9 +1,7 @@
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using System.Collections.Generic;
using Stride.LauncherApp.Services;
using Stride.Editor.CrashReport;
using Stride.LauncherApp.Services;
namespace Stride.LauncherApp
{

Просмотреть файл

@ -3,24 +3,24 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;
using Stride.Core.Assets.Editor;
using Stride.Core.Annotations;
using Stride.Core.Assets.Editor;
using Stride.Core.Extensions;
using Stride.Core.IO;
using Stride.Core.Packages;
using Stride.Core.Windows;
using Stride.PrivacyPolicy;
using Stride.LauncherApp.CrashReport;
using Stride.LauncherApp.Services;
using Stride.Metrics;
using Stride.PrivacyPolicy;
using Dispatcher = System.Windows.Threading.Dispatcher;
using Stride.Core.Packages;
using MessageBox = System.Windows.MessageBox;
using System.Diagnostics;
namespace Stride.LauncherApp
{
@ -55,7 +55,7 @@ namespace Stride.LauncherApp
/// <returns></returns>
internal static string GetExecutablePath()
{
return Process.GetCurrentProcess().MainModule.FileName;
return Environment.ProcessPath;
}
/// <summary>
@ -234,5 +234,5 @@ namespace Stride.LauncherApp
}
}
}

Просмотреть файл

@ -1,6 +1,5 @@
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using System.Collections.Generic;
namespace Stride.LauncherApp

Просмотреть файл

@ -1,7 +1,5 @@
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using System.Collections.Generic;
namespace Stride.LauncherApp
{
@ -21,7 +19,7 @@ namespace Stride.LauncherApp
// UpdateTargets errors: -101 to -200
ErrorUpdatingTargetFiles = -101, // We don't have a more accurate error for the moment.
// Uninstall errors: -201 to -300
UninstallCancelled = -201,
ErrorWhileUninstalling = -202, // We don't have a more accurate error for the moment.

Просмотреть файл

@ -1,8 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Stride.Core;
using Stride.Core.Packages;

Просмотреть файл

@ -0,0 +1,111 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
namespace Stride.LauncherApp
{
internal static class PrerequisitesValidator
{
private const string LauncherPrerequisites = @"Prerequisites\launcher-prerequisites.exe";
private static bool CheckDotNet4Version(int requiredVersion)
{
// Check for .NET v4 version
using (var ndpKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full"))
{
if (ndpKey == null)
return false;
int releaseKey = Convert.ToInt32(ndpKey.GetValue("Release"));
if (releaseKey < requiredVersion)
return false;
}
return true;
}
private static bool ValidateDotNet4Version(StringBuilder prerequisiteLog)
{
var result = true;
// Check for .NET 4.7.2+
// Note: it should now always be the case since renaming: Stride launcher is a separate forced setup to run, and it checks for 4.7.2.
// Still keeping code for future framework updates
if (!CheckDotNet4Version(461808))
{
prerequisiteLog.AppendLine("- .NET framework 4.7.2");
result = false;
}
// Everything passed
return result;
}
internal static void Validate(string[] args)
{
// Check prerequisites
var prerequisiteLog = new StringBuilder();
var prerequisitesFailedOnce = false;
while (!ValidateDotNet4Version(prerequisiteLog))
{
prerequisitesFailedOnce = true;
// Check if launcher prerequisite installer exists
if (!File.Exists(LauncherPrerequisites))
{
MessageBox.Show($"Some prerequisites are missing, but no prerequisite installer was found!\n\n{prerequisiteLog}\n\nPlease install them manually or report the problem.", "Prerequisite error", MessageBoxButtons.OK);
return;
}
// One of the prerequisite failed, launch the prerequisite installer
var prerequisitesApproved = MessageBox.Show($"Some prerequisites are missing, do you want to install them?\n\n{prerequisiteLog}", "Install missing prerequisites?", MessageBoxButtons.OKCancel);
if (prerequisitesApproved == DialogResult.Cancel)
return;
try
{
var prerequisitesInstallerProcess = Process.Start(LauncherPrerequisites);
if (prerequisitesInstallerProcess == null)
{
MessageBox.Show($"There was an error running the prerequisite installer {LauncherPrerequisites}.", "Prerequisite error", MessageBoxButtons.OK);
return;
}
prerequisitesInstallerProcess.WaitForExit();
}
catch
{
MessageBox.Show($"There was an error running the prerequisite installer {LauncherPrerequisites}.", "Prerequisite error", MessageBoxButtons.OK);
return;
}
prerequisiteLog.Length = 0;
}
if (!prerequisitesFailedOnce)
{
return;
}
// If prerequisites failed at least once, we want to restart ourselves to run with proper .NET framework
var exeLocation = Launcher.GetExecutablePath();
if (File.Exists(exeLocation))
{
// Forward arguments
for (int i = 0; i < args.Length; ++i)
{
// Quote arguments with spaces
if (args[i].IndexOf(' ') != -1)
args[i] = '\"' + args[i] + '\"';
}
var arguments = string.Join(" ", args);
// Start process
Process.Start(exeLocation, arguments);
}
return;
}
}
}

Просмотреть файл

@ -1,116 +1,16 @@
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
namespace Stride.LauncherApp
{
static class Program
{
private const string LauncherPrerequisites = @"Prerequisites\launcher-prerequisites.exe";
[STAThread]
private static void Main(string[] args)
{
// Check prerequisites
var prerequisiteLog = new StringBuilder();
var prerequisitesFailedOnce = false;
while (!CheckPrerequisites(prerequisiteLog))
{
prerequisitesFailedOnce = true;
// Check if launcher prerequisite installer exists
if (!File.Exists(LauncherPrerequisites))
{
MessageBox.Show($"Some prerequisites are missing, but no prerequisite installer was found!\n\n{prerequisiteLog}\n\nPlease install them manually or report the problem.", "Prerequisite error", MessageBoxButtons.OK);
return;
}
// One of the prerequisite failed, launch the prerequisite installer
var prerequisitesApproved = MessageBox.Show($"Some prerequisites are missing, do you want to install them?\n\n{prerequisiteLog}", "Install missing prerequisites?", MessageBoxButtons.OKCancel);
if (prerequisitesApproved == DialogResult.Cancel)
return;
try
{
var prerequisitesInstallerProcess = Process.Start(LauncherPrerequisites);
if (prerequisitesInstallerProcess == null)
{
MessageBox.Show($"There was an error running the prerequisite installer {LauncherPrerequisites}.", "Prerequisite error", MessageBoxButtons.OK);
return;
}
prerequisitesInstallerProcess.WaitForExit();
}
catch
{
MessageBox.Show($"There was an error running the prerequisite installer {LauncherPrerequisites}.", "Prerequisite error", MessageBoxButtons.OK);
return;
}
prerequisiteLog.Length = 0;
}
if (prerequisitesFailedOnce)
{
// If prerequisites failed at least once, we want to restart ourselves to run with proper .NET framework
var exeLocation = Launcher.GetExecutablePath();
if (File.Exists(exeLocation))
{
// Forward arguments
for (int i = 0; i < args.Length; ++i)
{
// Quote arguments with spaces
if (args[i].IndexOf(' ') != -1)
args[i] = '\"' + args[i] + '\"';
}
var arguments = string.Join(" ", args);
// Start process
Process.Start(exeLocation, arguments);
}
return;
}
PrerequisitesValidator.Validate(args);
Launcher.Main(args);
}
private static bool CheckPrerequisites(StringBuilder prerequisiteLog)
{
var result = true;
// Check for .NET 4.7.2+
// Note: it should now always be the case since renaming: Stride launcher is a separate forced setup to run, and it checks for 4.7.2.
// Still keeping code for future framework updates
if (!CheckDotNet4Version(461808))
{
prerequisiteLog.AppendLine("- .NET framework 4.7.2");
result = false;
}
// Everything passed
return result;
}
private static bool CheckDotNet4Version(int requiredVersion)
{
// Check for .NET v4 version
using (var ndpKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full"))
{
if (ndpKey == null)
return false;
int releaseKey = Convert.ToInt32(ndpKey.GetValue("Release"));
if (releaseKey < requiredVersion)
return false;
}
return true;
}
}
}

Просмотреть файл

@ -1,6 +1,5 @@
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;

Просмотреть файл

@ -6,8 +6,8 @@ using System.IO;
using System.Linq;
using Stride.Core.Assets.Editor;
using Stride.Core.Extensions;
using Stride.Core.MostRecentlyUsedFiles;
using Stride.Core.IO;
using Stride.Core.MostRecentlyUsedFiles;
using Stride.Core.Settings;
using Stride.Core.Yaml;

Просмотреть файл

@ -87,98 +87,99 @@ namespace Stride.LauncherApp.Services
var package = (packages.FirstOrDefault(x => x.Version > version && x.Version.SpecialVersion == "req") ?? packages.LastOrDefault());
// Check to see if an update is needed
if (package != null && version < new PackageVersion(package.Version.Version, package.Version.SpecialVersion))
if (package == null || version >= new PackageVersion(package.Version.Version, package.Version.SpecialVersion))
{
var windowCreated = new TaskCompletionSource<SelfUpdateWindow>();
var mainWindow = dispatcher.Invoke(() => Application.Current.MainWindow as LauncherWindow);
if (mainWindow == null)
throw new ApplicationException("Update requested without a Launcher Window. Cannot continue!");
return;
}
var windowCreated = new TaskCompletionSource<SelfUpdateWindow>();
var mainWindow = dispatcher.Invoke(() => Application.Current.MainWindow as LauncherWindow);
if (mainWindow == null)
throw new ApplicationException("Update requested without a Launcher Window. Cannot continue!");
dispatcher.InvokeAsync(() =>
dispatcher.InvokeAsync(() =>
{
selfUpdateWindow = new SelfUpdateWindow { Owner = mainWindow };
windowCreated.SetResult(selfUpdateWindow);
selfUpdateWindow.ShowDialog();
}).Forget();
var movedFiles = new List<string>();
// Download package
var installedPackage = await store.InstallPackage(package.Id, package.Version, package.TargetFrameworks, null);
// Copy files from tools\ to the current directory
var inputFiles = installedPackage.GetFiles();
var window = windowCreated.Task.Result;
dispatcher.Invoke(window.LockWindow);
// TODO: We should get list of previous files from nuspec (store it as a resource and open it with NuGet API maybe?)
// TODO: For now, we deal only with the App.config file since we won't be able to fix it afterward.
var exeLocation = Launcher.GetExecutablePath();
var exeDirectory = Path.GetDirectoryName(exeLocation);
const string directoryRoot = "tools/"; // Important!: this is matching where files are store in the nuspec
try
{
if (File.Exists(exeLocation))
{
selfUpdateWindow = new SelfUpdateWindow { Owner = mainWindow };
windowCreated.SetResult(selfUpdateWindow);
selfUpdateWindow.ShowDialog();
}).Forget();
Move(exeLocation, exeLocation + ".old");
movedFiles.Add(exeLocation);
}
var configLocation = exeLocation + ".config";
if (File.Exists(configLocation))
{
Move(configLocation, configLocation + ".old");
movedFiles.Add(configLocation);
}
foreach (var file in inputFiles.Where(file => file.Path.StartsWith(directoryRoot) && !file.Path.EndsWith("/")))
{
var fileName = Path.Combine(exeDirectory, file.Path.Substring(directoryRoot.Length));
var movedFiles = new List<string>();
// Move previous files to .old
if (File.Exists(fileName))
{
Move(fileName, fileName + ".old");
movedFiles.Add(fileName);
}
// Download package
var installedPackage = await store.InstallPackage(package.Id, package.Version, package.TargetFrameworks, null);
// Update the file
UpdateFile(fileName, file);
}
}
catch (Exception)
{
// Revert all olds files if a file didn't work well
foreach (var oldFile in movedFiles)
{
Move(oldFile + ".old", oldFile);
}
throw;
}
// Copy files from tools\ to the current directory
var inputFiles = installedPackage.GetFiles();
var window = windowCreated.Task.Result;
dispatcher.Invoke(window.LockWindow);
// TODO: We should get list of previous files from nuspec (store it as a resource and open it with NuGet API maybe?)
// TODO: For now, we deal only with the App.config file since we won't be able to fix it afterward.
var exeLocation = Launcher.GetExecutablePath();
var exeDirectory = Path.GetDirectoryName(exeLocation);
const string directoryRoot = "tools/"; // Important!: this is matching where files are store in the nuspec
// Remove .old files
foreach (var oldFile in movedFiles)
{
try
{
if (File.Exists(exeLocation))
{
Move(exeLocation, exeLocation + ".old");
movedFiles.Add(exeLocation);
}
var configLocation = exeLocation + ".config";
if (File.Exists(configLocation))
{
Move(configLocation, configLocation + ".old");
movedFiles.Add(configLocation);
}
foreach (var file in inputFiles.Where(file => file.Path.StartsWith(directoryRoot) && !file.Path.EndsWith("/")))
{
var fileName = Path.Combine(exeDirectory, file.Path.Substring(directoryRoot.Length));
var renamedPath = oldFile + ".old";
// Move previous files to .old
if (File.Exists(fileName))
{
Move(fileName, fileName + ".old");
movedFiles.Add(fileName);
}
// Update the file
UpdateFile(fileName, file);
if (File.Exists(renamedPath))
{
File.Delete(renamedPath);
}
}
catch (Exception)
{
// Revert all olds files if a file didn't work well
foreach (var oldFile in movedFiles)
{
Move(oldFile + ".old", oldFile);
}
throw;
// All the files have been replaced, we let it go even if we cannot remove all the old files.
}
// Remove .old files
foreach (var oldFile in movedFiles)
{
try
{
var renamedPath = oldFile + ".old";
if (File.Exists(renamedPath))
{
File.Delete(renamedPath);
}
}
catch (Exception)
{
// All the files have been replaced, we let it go even if we cannot remove all the old files.
}
}
// Clean cache from files obtain via package.GetFiles above.
store.PurgeCache();
dispatcher.Invoke(RestartApplication);
}
// Clean cache from files obtain via package.GetFiles above.
store.PurgeCache();
dispatcher.Invoke(RestartApplication);
}
private static void Move(string oldPath, string newPath)
@ -238,10 +239,7 @@ namespace Stride.LauncherApp.Services
{
await dispatcher.InvokeAsync(() =>
{
if (selfUpdateWindow != null)
{
selfUpdateWindow.ForceClose();
}
selfUpdateWindow?.ForceClose();
});
await dialogService.MessageBox(string.Format(Strings.NewVersionDownloadError, e.Message), MessageBoxButton.OK, MessageBoxImage.Error);
@ -261,10 +259,8 @@ namespace Stride.LauncherApp.Services
private static void UpdateFile(string newFilePath, PackageFile file)
{
EnsureDirectory(newFilePath);
using (Stream fromStream = file.GetStream(), toStream = File.Create(newFilePath))
{
fromStream.CopyTo(toStream);
}
using Stream fromStream = file.GetStream(), toStream = File.Create(newFilePath);
fromStream.CopyTo(toStream);
}
public static void RestartApplication()

Просмотреть файл

@ -5,7 +5,6 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Stride.Core.Extensions;
using Stride.Core.VisualStudio;
using Stride.Core.Packages;
using Stride.Core.Presentation.Services;
using Stride.Core.Presentation.ViewModel;
@ -17,7 +16,7 @@ namespace Stride.LauncherApp.Services
private readonly IViewModelServiceProvider serviceProvider;
private readonly NugetStore store;
internal UninstallHelper(IViewModelServiceProvider serviceProvider, NugetStore store)
internal UninstallHelper(IViewModelServiceProvider serviceProvider, NugetStore store)
{
this.serviceProvider = serviceProvider;
this.store = store;
@ -110,7 +109,7 @@ namespace Stride.LauncherApp.Services
// Can probably be improved (not sure how stable and unique path could be?)
return (path.IndexOf(folder, StringComparison.OrdinalIgnoreCase) != -1);
}
private static List<Process> CollectPackageProcesses(string installPath)
{
var result = new List<Process>();
@ -125,7 +124,7 @@ namespace Stride.LauncherApp.Services
continue;
// Discard ourselves
if (process.Id == Process.GetCurrentProcess().Id)
if (process.Id == Environment.ProcessId)
continue;
result.Add(process);

Просмотреть файл

@ -66,10 +66,8 @@ namespace Stride.LauncherApp.ViewModels
if (stream == null)
return null;
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
}
catch (Exception)

Просмотреть файл

@ -6,10 +6,10 @@ using System.Diagnostics;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Stride.LauncherApp.Resources;
using Stride.Core.Presentation.Commands;
using Stride.Core.Presentation.Services;
using Stride.Core.Presentation.ViewModel;
using Stride.LauncherApp.Resources;
namespace Stride.LauncherApp.ViewModels
{
@ -75,35 +75,36 @@ namespace Stride.LauncherApp.ViewModels
string urlData;
try
{
using (var response = await httpClient.GetAsync(string.Format(Urls.GettingStarted, version)))
{
response.EnsureSuccessStatusCode();
urlData = await response.Content.ReadAsStringAsync();
using var response = await httpClient.GetAsync(string.Format(Urls.GettingStarted, version));
response.EnsureSuccessStatusCode();
urlData = await response.Content.ReadAsStringAsync();
if (urlData != null)
{
var urls = urlData.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var url in urls)
{
var match = ParsingRegex.Match(url);
if (match.Success && match.Groups.Count == 4)
{
var link = match.Groups[3].Value;
if (link.StartsWith(DocPageScheme))
{
link = GetDocumentationPageUrl(version, link.Substring(DocPageScheme.Length));
}
var page = new DocumentationPageViewModel(serviceProvider, version)
{
Title = match.Groups[1].Value.Trim(),
Description = match.Groups[2].Value.Trim(),
Url = link.Trim()
};
result.Add(page);
}
}
}
if (urlData == null)
{
return result;
}
var urls = urlData.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var url in urls)
{
var match = ParsingRegex.Match(url);
if (!match.Success || match.Groups.Count != 4)
{
continue;
}
var link = match.Groups[3].Value;
if (link.StartsWith(DocPageScheme))
{
link = GetDocumentationPageUrl(version, link.Substring(DocPageScheme.Length));
}
var page = new DocumentationPageViewModel(serviceProvider, version)
{
Title = match.Groups[1].Value.Trim(),
Description = match.Groups[2].Value.Trim(),
Url = link.Trim()
};
result.Add(page);
}
return result;
}
catch (Exception)
{

Просмотреть файл

@ -1,7 +1,5 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using NuGet.Frameworks;
using Stride.Core.Annotations;
using Stride.Core.Presentation.ValueConverters;

Просмотреть файл

@ -38,7 +38,7 @@ namespace Stride.LauncherApp.ViewModels
private bool isOffline;
private bool isSynchronizing = true;
private string currentToolTip;
private List<(DateTime Time, MessageLevel Level, string Message)> logMessages = new List<(DateTime, MessageLevel, string)>();
private List<(DateTime Time, MessageLevel Level, string Message)> logMessages = new();
private bool autoCloseLauncher = LauncherSettings.CloseLauncherAutomatically;
private bool lastActiveVersionRestored;
private AnnouncementViewModel announcement;
@ -48,9 +48,8 @@ namespace Stride.LauncherApp.ViewModels
internal LauncherViewModel(IViewModelServiceProvider serviceProvider, NugetStore store)
: base(serviceProvider)
{
if (store == null) throw new ArgumentNullException(nameof(store));
DependentProperties.Add("ActiveVersion", new[] { "ActiveDocumentationPages" });
this.store = store;
this.store = store ?? throw new ArgumentNullException(nameof(store));
store.Logger = this;
DisplayReleaseAnnouncement();
@ -70,16 +69,17 @@ namespace Stride.LauncherApp.ViewModels
CheckDeprecatedSourcesCommand = new AnonymousTaskCommand(ServiceProvider, async () =>
{
var settings = NuGet.Configuration.Settings.LoadDefaultSettings(null);
if (!NugetStore.CheckPackageSource(settings, "Stride"))
if (NugetStore.CheckPackageSource(settings, "Stride"))
{
// Add Stride package store (still used for Xenko up to 3.0)
if (await ServiceProvider.Get<IDialogService>().MessageBox(Strings.AskAddNugetDeprecatedSource, MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
{
NugetStore.UpdatePackageSource(settings, "Stride", "https://packages.stride3d.net/nuget");
settings.SaveToDisk();
return;
}
// Add Stride package store (still used for Xenko up to 3.0)
if (await ServiceProvider.Get<IDialogService>().MessageBox(Strings.AskAddNugetDeprecatedSource, MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
{
NugetStore.UpdatePackageSource(settings, "Stride", "https://packages.stride3d.net/nuget");
settings.SaveToDisk();
SelfUpdater.RestartApplication();
}
SelfUpdater.RestartApplication();
}
});
@ -233,7 +233,7 @@ namespace Stride.LauncherApp.ViewModels
=> (obj.Id.GetHashCode() ^ obj.Version.ToString().GetHashCode());
}
private HashSet<NugetLocalPackage> referencedPackages = new HashSet<NugetLocalPackage>(ReferencedPackageEqualityComparer.Instance);
private HashSet<NugetLocalPackage> referencedPackages = new(ReferencedPackageEqualityComparer.Instance);
private async Task RemoveUnusedPackages(IEnumerable<NugetLocalPackage> mainPackages)
{
@ -254,15 +254,17 @@ namespace Stride.LauncherApp.ViewModels
foreach (var dependency in package.Dependencies)
{
string prefix = dependency.Item1.Split('.', 2)[0];
if ((prefix == "Stride") || (prefix == "Xenko"))
if (prefix is not "Stride" and not "Xenko")
{
NugetLocalPackage dependencyPackage = store.FindLocalPackage(dependency.Item1, dependency.Item2);
if ((dependencyPackage != null) && (!referencedPackages.Contains(dependencyPackage)))
{
referencedPackages.Add(dependencyPackage);
await FindReferencedPackages(dependencyPackage);
}
continue;
}
NugetLocalPackage dependencyPackage = store.FindLocalPackage(dependency.Item1, dependency.Item2);
if (dependencyPackage == null || referencedPackages.Contains(dependencyPackage))
{
continue;
}
referencedPackages.Add(dependencyPackage);
await FindReferencedPackages(dependencyPackage);
}
}
@ -324,7 +326,7 @@ namespace Stride.LauncherApp.ViewModels
Dispatcher.Invoke(() =>
{
foreach (var strideUninstalledVersion in strideVersions.OfType<StrideStoreVersionViewModel>().Where(x => !updatedLocalPackages.Contains(x)))
strideUninstalledVersion.UpdateLocalPackage(null, new NugetLocalPackage[0]);
strideUninstalledVersion.UpdateLocalPackage(null, Array.Empty<NugetLocalPackage>());
});
// Update the active version if it is now invalid.
@ -380,8 +382,7 @@ namespace Stride.LauncherApp.ViewModels
if (version is StrideDevVersionViewModel)
project.CompatibleVersions.Add(version);
var storeVersion = version as StrideStoreVersionViewModel;
if (storeVersion != null && storeVersion.CanDelete)
if (version is StrideStoreVersionViewModel storeVersion && storeVersion.CanDelete)
{
// Discard the version that matches the recent project version
if (project.StrideVersion == new Version(storeVersion.Version.Version.Major, storeVersion.Version.Version.Minor))
@ -403,7 +404,12 @@ namespace Stride.LauncherApp.ViewModels
{
try
{
var serverPackages = await RunLockTask(() => store.FindSourcePackages(store.MainPackageIds, CancellationToken.None).Result.FilterStrideMainPackages().Where(p => !store.IsDevRedirectPackage(p)).OrderByDescending(p => p.Version).ToList());
var serverPackages = await RunLockTask(() => store
.FindSourcePackages(store.MainPackageIds, CancellationToken.None).Result
.FilterStrideMainPackages()
.Where(p => !store.IsDevRedirectPackage(p))
.OrderByDescending(p => p.Version)
.ToList());
// Check if we could connect to the server
var wasOffline = IsOffline;
@ -567,8 +573,7 @@ namespace Stride.LauncherApp.ViewModels
var mainExecutable = ActiveVersion.LocateMainExecutable();
// If version is older than 1.2.0, than we need to log the usage of older version
var activeStoreVersion = ActiveVersion as StrideStoreVersionViewModel;
if (activeStoreVersion != null && activeStoreVersion.Version.Version < new Version(1, 2, 0, 0))
if (ActiveVersion is StrideStoreVersionViewModel activeStoreVersion && activeStoreVersion.Version.Version < new Version(1, 2, 0, 0))
{
metricsForEditorBefore120 = new MetricsClient(CommonApps.StrideEditorAppId, versionOverride: activeStoreVersion.Version.ToString());
}

Просмотреть файл

@ -4,14 +4,13 @@ using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Xml;
using Stride.LauncherApp.Resources;
using Stride.Core.Presentation.Commands;
using Stride.Core.Presentation.Services;
using Stride.Core.Presentation.ViewModel;
using Stride.LauncherApp.Resources;
namespace Stride.LauncherApp.ViewModels
{
@ -67,42 +66,38 @@ namespace Stride.LauncherApp.ViewModels
var result = new List<NewsPageViewModel>();
try
{
using (var response = await httpClient.GetAsync(Urls.RssFeed))
using var response = await httpClient.GetAsync(Urls.RssFeed);
response.EnsureSuccessStatusCode();
var rss = await response.Content.ReadAsStreamAsync();
if (rss.Length == 0)
return result;
int count = 0;
using XmlReader rssReader = XmlReader.Create(rss);
rssReader.MoveToContent();
while (rssReader.ReadToFollowing("item") && count < maxCount)
{
response.EnsureSuccessStatusCode();
var rss = await response.Content.ReadAsStreamAsync();
if (rss.Length == 0)
return result;
int count = 0;
using (XmlReader rssReader = XmlReader.Create(rss))
rssReader.ReadToFollowing("title");
string title = rssReader.Read() ? rssReader.Value : null;
rssReader.ReadToFollowing("description");
string description = rssReader.Read() ? rssReader.Value : null;
rssReader.ReadToFollowing("pubDate");
var date = new DateTime();
bool dateValid = rssReader.Read() && DateTime.TryParseExact(rssReader.Value, "ddd, dd MMM yyyy HH:mm:ss zz00", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
rssReader.ReadToFollowing("link");
string link = rssReader.Read() ? rssReader.Value : null;
if (dateValid && title != null && link != null && description != null)
{
rssReader.MoveToContent();
while (rssReader.ReadToFollowing("item") && count < maxCount)
var page = new NewsPageViewModel(serviceProvider)
{
rssReader.ReadToFollowing("title");
string title = rssReader.Read() ? rssReader.Value : null;
rssReader.ReadToFollowing("description");
string description = rssReader.Read() ? rssReader.Value : null;
rssReader.ReadToFollowing("pubDate");
var date = new DateTime();
bool dateValid = rssReader.Read() && DateTime.TryParseExact(rssReader.Value, "ddd, dd MMM yyyy HH:mm:ss zz00", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
rssReader.ReadToFollowing("link");
string link = rssReader.Read() ? rssReader.Value : null;
if (dateValid && title != null && link != null && description != null)
{
var page = new NewsPageViewModel(serviceProvider)
{
Title = title,
Url = link,
Description = description,
Date = date
};
result.Add(page);
++count;
}
}
Title = title,
Url = link,
Description = description,
Date = date
};
result.Add(page);
++count;
}
}
}

Просмотреть файл

@ -35,10 +35,8 @@ namespace Stride.LauncherApp.ViewModels
internal PackageVersionViewModel(LauncherViewModel launcher, NugetStore store, NugetLocalPackage localPackage)
: base(launcher.SafeArgument("launcher").ServiceProvider)
{
if (launcher == null) throw new ArgumentNullException(nameof(launcher));
if (store == null) throw new ArgumentNullException(nameof(store));
Launcher = launcher;
Store = store;
Launcher = launcher ?? throw new ArgumentNullException(nameof(launcher));
Store = store ?? throw new ArgumentNullException(nameof(store));
LocalPackage = localPackage;
DownloadCommand = new AnonymousTaskCommand(ServiceProvider, () => Download(true));
DeleteCommand = new AnonymousTaskCommand(ServiceProvider, () => Delete(true, true)) { IsEnabled = CanDelete };
@ -184,13 +182,11 @@ namespace Stride.LauncherApp.ViewModels
try
{
CurrentProcessStatus = null;
using (var progressReport = new ProgressReport(Store, ServerPackage))
{
progressReport.ProgressChanged += (action, progress) => { Dispatcher.InvokeAsync(() => { UpdateProgress(action, progress); }).Forget(); };
progressReport.UpdateProgress(ProgressAction.Delete, -1);
await Store.UninstallPackage(LocalPackage, progressReport);
CurrentProcessStatus = null;
}
using var progressReport = new ProgressReport(Store, ServerPackage);
progressReport.ProgressChanged += (action, progress) => { Dispatcher.InvokeAsync(() => { UpdateProgress(action, progress); }).Forget(); };
progressReport.UpdateProgress(ProgressAction.Delete, -1);
await Store.UninstallPackage(LocalPackage, progressReport);
CurrentProcessStatus = null;
}
catch (Exception e)
{

Просмотреть файл

@ -7,11 +7,11 @@ using System.Threading.Tasks;
using Stride.Core.Assets;
using Stride.Core.Extensions;
using Stride.Core.IO;
using Stride.LauncherApp.Resources;
using Stride.Core.Presentation.Collections;
using Stride.Core.Presentation.Commands;
using Stride.Core.Presentation.Services;
using Stride.Core.Presentation.ViewModel;
using Stride.LauncherApp.Resources;
using Stride.LauncherApp.Services;
namespace Stride.LauncherApp.ViewModels
@ -79,24 +79,24 @@ namespace Stride.LauncherApp.ViewModels
private void Remove()
{
//Remove files that's was deleted or upgraded by stride versions <= 3.0
if (string.IsNullOrEmpty(this.StrideVersionName) || string.Compare(this.StrideVersionName, "3.0", StringComparison.Ordinal) <= 0)
if (string.IsNullOrEmpty(StrideVersionName) || string.Compare(StrideVersionName, "3.0", StringComparison.Ordinal) <= 0)
{
//Get all installed versions
var strideInstalledVersions = this.Launcher.StrideVersions.Where(x => x.CanDelete)
var strideInstalledVersions = Launcher.StrideVersions.Where(x => x.CanDelete)
.Select(x => $"{x.Major}.{x.Minor}").ToList();
//If original version of files is not in list get and to add it.
if (!string.IsNullOrEmpty(this.StrideVersionName) && !strideInstalledVersions.Any(x => x.Equals(this.StrideVersionName)))
strideInstalledVersions.Add(this.StrideVersionName);
if (!string.IsNullOrEmpty(StrideVersionName) && !strideInstalledVersions.Any(x => x.Equals(StrideVersionName)))
strideInstalledVersions.Add(StrideVersionName);
foreach (var item in strideInstalledVersions)
{
GameStudioSettings.RemoveMostRecentlyUsed(this.fullPath, item);
GameStudioSettings.RemoveMostRecentlyUsed(fullPath, item);
}
}
else
{
GameStudioSettings.RemoveMostRecentlyUsed(this.fullPath, this.StrideVersionName);
GameStudioSettings.RemoveMostRecentlyUsed(fullPath, StrideVersionName);
}
}

Просмотреть файл

@ -74,11 +74,9 @@ namespace Stride.LauncherApp.ViewModels
try
{
using (var response = await httpClient.GetAsync($"{BaseUrl}{ReleaseNotesFileName}"))
{
response.EnsureSuccessStatusCode();
releaseNotesMarkdown = await response.Content.ReadAsStringAsync();
}
using var response = await httpClient.GetAsync($"{BaseUrl}{ReleaseNotesFileName}");
response.EnsureSuccessStatusCode();
releaseNotesMarkdown = await response.Content.ReadAsStringAsync();
}
catch (Exception)
{

Просмотреть файл

@ -1,8 +1,3 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Stride.Core;
using Stride.Core.Annotations;
using Stride.Core.Packages;
@ -49,9 +44,7 @@ namespace Stride.LauncherApp.ViewModels
{
get
{
if (LocalPackage != null)
return $"{LocalPackage.Id} {LocalPackage.Version} (installed)";
return $"{ServerPackage.Id} {ServerPackage.Version}";
return LocalPackage != null ? $"{LocalPackage.Id} {LocalPackage.Version} (installed)" : $"{ServerPackage.Id} {ServerPackage.Version}";
}
}

Просмотреть файл

@ -1,19 +1,17 @@
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Stride.Core;
using Stride.Core.Extensions;
using Stride.LauncherApp.Resources;
using Stride.Core.Packages;
using Stride.Core.Presentation.Collections;
using Stride.Core.Presentation.Commands;
using Stride.Core.Presentation.Services;
using System.Collections.Generic;
using System.Linq;
using Stride.LauncherApp.Resources;
namespace Stride.LauncherApp.ViewModels
{
@ -49,7 +47,7 @@ namespace Stride.LauncherApp.ViewModels
{
get
{
return (LatestServerPackage?.Source != null) && (Uri.IsWellFormedUriString(LatestServerPackage.Source, UriKind.Absolute));
return (LatestServerPackage?.Source != null) && Uri.IsWellFormedUriString(LatestServerPackage.Source, UriKind.Absolute);
}
}

Просмотреть файл

@ -38,45 +38,46 @@ namespace Stride.LauncherApp.ViewModels
protected void UpdateFrameworks()
{
Frameworks.Clear();
if (LocalPackage != null && InstallPath != null)
if (LocalPackage == null || InstallPath == null)
{
foreach (var toplevelFolder in new[] { "tools", "lib" })
return;
}
foreach (var toplevelFolder in new[] { "tools", "lib" })
{
var libDirectory = Path.Combine(InstallPath, toplevelFolder);
if (Directory.Exists(libDirectory))
{
var libDirectory = Path.Combine(InstallPath, toplevelFolder);
if (Directory.Exists(libDirectory))
foreach (var frameworkPath in Directory.EnumerateDirectories(libDirectory))
{
foreach (var frameworkPath in Directory.EnumerateDirectories(libDirectory))
if (File.Exists(Path.Combine(frameworkPath, Major >= 4 ? StrideGameStudioExe : XenkoGameStudioExe)))
{
if (File.Exists(Path.Combine(frameworkPath, Major >= 4 ? StrideGameStudioExe : XenkoGameStudioExe)))
{
Frameworks.Add(new DirectoryInfo(frameworkPath).Name);
}
Frameworks.Add(new DirectoryInfo(frameworkPath).Name);
}
}
}
}
if (Frameworks.Count > 0)
if (Frameworks.Count > 0)
{
try
{
try
// If preferred framework exists in our list, select it
var preferredFramework = LauncherSettings.PreferredFramework;
if (Frameworks.Contains(preferredFramework))
SelectedFramework = preferredFramework;
else
{
// If preferred framework exists in our list, select it
var preferredFramework = LauncherSettings.PreferredFramework;
if (Frameworks.Contains(preferredFramework))
SelectedFramework = preferredFramework;
else
{
// Otherwise, try to find a framework of the same kind (.NET Core or .NET Framework)
var nugetFramework = NuGetFramework.ParseFolder(preferredFramework);
SelectedFramework =
Frameworks.FirstOrDefault(x => NuGetFramework.ParseFolder(preferredFramework).Framework == nugetFramework.Framework)
?? Frameworks.First(); // otherwise fallback to first choice
}
}
catch
{
SelectedFramework = Frameworks.First();
// Otherwise, try to find a framework of the same kind (.NET Core or .NET Framework)
var nugetFramework = NuGetFramework.ParseFolder(preferredFramework);
SelectedFramework =
Frameworks.FirstOrDefault(x => NuGetFramework.ParseFolder(preferredFramework).Framework == nugetFramework.Framework)
?? Frameworks.First(); // otherwise fallback to first choice
}
}
catch
{
SelectedFramework = Frameworks.First();
}
}
}
@ -140,7 +141,7 @@ namespace Stride.LauncherApp.ViewModels
return $"{packageSimpleName} {majorVersion}.{minorVersion}";
}
/// <summary>
/// Indicates if the given version corresponds to a beta version.
/// </summary>

Просмотреть файл

@ -62,7 +62,7 @@ namespace Stride.LauncherApp.ViewModels
await UpdateVersionsFromStore();
Dispatcher.Invoke(UpdateStatus);
}
/// <inheritdoc/>
protected override void UpdateStatus()
{
@ -114,7 +114,7 @@ namespace Stride.LauncherApp.ViewModels
/// <inheritdoc/>
protected override async Task UpdateVersionsFromStore()
{
var versionRange = Store.VsixVersionToStrideRelease[this.vsixSupportedVsVersion];
var versionRange = Store.VsixVersionToStrideRelease[vsixSupportedVsVersion];
var minVersion = versionRange.MinVersion;
var maxVersion = versionRange.MaxVersion;

Просмотреть файл

@ -2,21 +2,18 @@
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Interop;
using Stride.LauncherApp.Services;
using Stride.LauncherApp.ViewModels;
using Stride.Core.Packages;
using Stride.Core.Presentation.Dialogs;
using Stride.Core.Presentation.Extensions;
using Stride.Core.Presentation.View;
using Stride.Core.Presentation.ViewModel;
using NuGet.Frameworks;
using Stride.LauncherApp.Services;
using Stride.LauncherApp.ViewModels;
namespace Stride.LauncherApp.Views
{
@ -25,7 +22,7 @@ namespace Stride.LauncherApp.Views
/// </summary>
public partial class LauncherWindow
{
public LauncherWindow()
{
InitializeComponent();
@ -51,14 +48,14 @@ namespace Stride.LauncherApp.Views
}
public bool ExitOnUserClose { get; set; }
private LauncherViewModel ViewModel => (LauncherViewModel)DataContext;
internal void Initialize(NugetStore store, string defaultLogText = null)
{
var dispatcherService = new DispatcherService(Dispatcher);
var dialogService = new DialogService(dispatcherService, Launcher.ApplicationName);
var serviceProvider = new ViewModelServiceProvider(new object[] {dispatcherService, dialogService});
var serviceProvider = new ViewModelServiceProvider(new object[] { dispatcherService, dialogService });
DataContext = new LauncherViewModel(serviceProvider, store);
}
@ -78,7 +75,7 @@ namespace Stride.LauncherApp.Views
}
var viewModel = (LauncherViewModel)DataContext;
LauncherSettings.ActiveVersion = viewModel.ActiveVersion != null ? viewModel.ActiveVersion.Name : "";
LauncherSettings.ActiveVersion = viewModel.ActiveVersion != null ? viewModel.ActiveVersion.Name : "";
LauncherSettings.Save();
if (ExitOnUserClose)
Environment.Exit(1);

Просмотреть файл

@ -1,8 +1,3 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;