Beispiel #1
0
    private static bool DisplayMessage(string title, string message, Actions.DisplayMessageBoxParams parameters)
    {
        ReloadedWindow window = parameters.Type switch
        {
            Actions.MessageBoxType.Ok => new Pages.Dialogs.MessageBox(title, message),
            Actions.MessageBoxType.OkCancel => new MessageBoxOkCancel(title, message),
            _ => throw new ArgumentOutOfRangeException()
        };

        window.WindowStartupLocation = (WindowStartupLocation)parameters.StartupLocation;
        if (parameters.Width != default)
        {
            window.SizeToContent = SizeToContent.Height;
            window.Width         = parameters.Width;
        }

        if (parameters.Timeout != default)
        {
            // Close window after timeout if open.
            Task.Delay(parameters.Timeout).ContinueWith(o =>
            {
                ActionWrappers.ExecuteWithApplicationDispatcher(() =>
                {
                    if (Application.Current.Windows.Cast <Window>().Any(x => x == window))
                    {
                        window.Close();
                    }
                });
            });
        }

        var result = window.ShowDialog();

        return(result.HasValue && result.Value);
    }
Beispiel #2
0
        /// <summary>
        /// Checks if there are updates for any of the installed mods and/or new dependencies to fetch.
        /// </summary>
        public static async Task <bool> CheckForModUpdatesAsync()
        {
            if (!_hasInternetConnection)
            {
                return(false);
            }

            var modConfigService = IoC.Get <ModConfigService>();
            var allMods          = modConfigService.Mods.Select(x => new PathTuple <ModConfig>(x.Path, (ModConfig)x.Config)).ToArray();

            try
            {
                var updater       = new Updater(allMods, new UpdaterData(IoC.Get <AggregateNugetRepository>()));
                var updateDetails = await updater.GetUpdateDetails();

                if (updateDetails.HasUpdates())
                {
                    ActionWrappers.ExecuteWithApplicationDispatcher(() =>
                    {
                        var dialog = new ModUpdateDialog(updater, updateDetails);
                        dialog.ShowDialog();
                    });

                    return(true);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + "|" + e.StackTrace);
                return(false);
            }

            return(false);
        }
    /// <summary>
    /// Executes the task asynchronously.
    /// </summary>
    /// <returns></returns>
    public async Task ExecuteAsync()
    {
        var config = _application.Config;

        await using var fileStream = new FileStream(ApplicationConfig.GetAbsoluteAppLocation(_application), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 524288);
        var indexApi = new IndexApi();
        var index    = await indexApi.GetIndexAsync();

        var hash         = Hashing.ToString(await Hashing.FromStreamAsync(fileStream));
        var applications = index.FindApplication(hash, config.AppId, out bool hashMatches);

        await await ActionWrappers.ExecuteWithApplicationDispatcherAsync(async() =>
        {
            if (applications.Count == 1 && hashMatches)
            {
                ApplyIndexEntry(await indexApi.GetApplicationAsync(applications[0]), _application, hash);
            }
            else if (applications.Count >= 1)
            {
                // Select application.
                var viewModel = new SelectAddedGameDialogViewModel(applications);
                var result    = Actions.ShowSelectAddedGameDialog(viewModel);
                if (result == null)
                {
                    return;
                }

                ApplyIndexEntry(await indexApi.GetApplicationAsync(result), _application, hash);
            }
        });
    }
Beispiel #4
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ActionWrappers.ExecuteWithApplicationDispatcher(() =>
            {
                void Update()
                {
                    ViewModel.Updater
                    .Update(ViewModel.Summary, new Progress <double>(d => { ViewModel.Progress = (int)(d * 100); }))
                    .ContinueWith(x => ActionWrappers.ExecuteWithApplicationDispatcher(this.Close));
                }

                if (ApplicationInstanceTracker.GetAllProcesses(out _))
                {
                    var messageBox = new MessageBoxOkCancel(_xamlUpdateModConfirmTitle.Get(), _xamlUpdateModConfirmMessage.Get());
                    messageBox.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    messageBox.ShowDialog();

                    if (messageBox.DialogResult.HasValue && messageBox.DialogResult.Value)
                    {
                        Update();
                    }
                }
                else
                {
                    Update();
                }
            });
        }
Beispiel #5
0
    /// <summary>
    /// Performs an update of the mod loader.
    /// </summary>
    public async Task Update()
    {
        if (ApplicationInstanceTracker.GetAllProcesses(out var processes))
        {
            ActionWrappers.ExecuteWithApplicationDispatcher(() =>
            {
                // Accumulate list of processes.
                string allProcessString = $"\n{Resources.UpdateLoaderProcessList.Get()}:";
                foreach (var process in processes)
                {
                    allProcessString += $"\n({process.Id}) {process.ProcessName}";
                }

                Actions.DisplayMessagebox.Invoke(Resources.UpdateLoaderRunningTitle.Get(), Resources.UpdateLoaderRunningMessage.Get() + allProcessString, new Actions.DisplayMessageBoxParams()
                {
                    StartupLocation = Actions.WindowStartupLocation.CenterScreen
                });
            });
        }
        else
        {
            _manager.OnApplySelfUpdate += OnApplySelfUpdate;
            await _manager.PrepareUpdateAsync(_targetVersion, new Progress <double>(d => { Progress = d * 100; }));

            await _manager.StartUpdateAsync(_targetVersion, new OutOfProcessOptions()
            {
                Restart = true
            }, new UpdateOptions()
            {
                CleanupAfterUpdate = true
            });

            Environment.Exit(0);
        }
    }
 public void Dispose()
 {
     ActionWrappers.ExecuteWithApplicationDispatcher(() => _modsViewSource.Filter -= ModsViewSourceOnFilter);
     AnimateOutFinished -= Dispose;
     ViewModel?.Dispose();
     GC.SuppressFinalize(this);
 }
Beispiel #7
0
        public async Task Update()
        {
            if (ApplicationInstanceTracker.GetAllProcesses(out var processes))
            {
                ActionWrappers.ExecuteWithApplicationDispatcher(() =>
                {
                    // Accumulate list of processes.
                    string allProcessString = $"\n{_xamlUpdateLoaderProcessList.Get()}:";
                    foreach (var process in processes)
                    {
                        allProcessString += $"\n({process.Id}) {process.ProcessName}";
                    }

                    var box = new MessageBox(_xamlUpdateLoaderRunningTitle.Get(), _xamlUpdateLoaderRunningMessage.Get() + allProcessString);
                    box.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    box.ShowDialog();
                });
            }
            else
            {
                await _manager.PrepareUpdateAsync(_targetVersion, new Progress <double>(d => { Progress = (int)(d * 100); }));

                _manager.LaunchUpdater(_targetVersion, true);
                Environment.Exit(0);
            }
        }
Beispiel #8
0
 public void Dispose()
 {
     this.AnimateOutStarted -= Dispose;
     ActionWrappers.ExecuteWithApplicationDispatcher(() => PageHost.CurrentPage?.AnimateOut());
     ViewModel?.Dispose();
     GC.SuppressFinalize(this);
 }
Beispiel #9
0
        /// <summary>
        /// Checks if there are any updates for the mod loader.
        /// </summary>
        public static async Task CheckForLoaderUpdatesAsync()
        {
            // Check for loader updates.
            try
            {
                using (var manager = new UpdateManager(
                           new GithubPackageResolver("Reloaded-Project", "Reloaded-II", "Release.zip"),
                           new ArchiveExtractor()))
                {
                    // Check for new version and, if available, perform full update and restart
                    var result = await manager.CheckForUpdatesAsync();

                    if (result.CanUpdate)
                    {
                        ActionWrappers.ExecuteWithApplicationDispatcher(() =>
                        {
                            var dialog = new ModLoaderUpdateDialog(manager, result.LastVersion);
                            dialog.ShowDialog();
                        });
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show(_xamlCheckUpdatesFailed.Get());
            }
        }
Beispiel #10
0
        public ReloadedAppViewModel(ApplicationViewModel applicationViewModel)
        {
            ApplicationViewModel = applicationViewModel;
            ApplicationViewModel.SelectedProcess.EnableRaisingEvents = true;
            ApplicationViewModel.SelectedProcess.Exited += SelectedProcessOnExited;

            /* Try establish connection. */
            int port = 0;

            try
            {
                port = ActionWrappers.TryGetValue(GetPort, _xamlModLoaderSetupTimeout.Get(), _xamlModLoaderSetupSleepTime.Get());
            }
            catch (Exception ex)
            {
                Errors.HandleException(new Exception(Errors.ErrorFailedToObtainPort(), ex));
                return;
            }

            Client = new Client(port);
            Client.OnReceiveException += ClientOnReceiveException;
            Refresh();

            _refreshTimer           = new System.Timers.Timer(_xamlModLoaderRefreshInterval.Get());
            _refreshTimer.AutoReset = true;
            _refreshTimer.Elapsed  += (sender, args) => Refresh();
            _refreshTimer.Enabled   = true;
        }
Beispiel #11
0
        /// <summary>
        /// Checks if there are any updates for the mod loader.
        /// </summary>
        public static async Task CheckForLoaderUpdatesAsync()
        {
            if (!_hasInternetConnection)
            {
                return;
            }

            // Check for loader updates.
            try
            {
                using (var manager = new UpdateManager(
                           new GithubPackageResolver(Misc.Constants.GitRepositoryAccount, Misc.Constants.GitRepositoryName, Constants.GitRepositoryReleaseName),
                           new ArchiveExtractor()))
                {
                    // Check for new version and, if available, perform full update and restart
                    var result = await manager.CheckForUpdatesAsync();

                    if (result.CanUpdate)
                    {
                        ActionWrappers.ExecuteWithApplicationDispatcher(() =>
                        {
                            var dialog = new ModLoaderUpdateDialog(manager, result.LastVersion);
                            dialog.ShowDialog();
                        });
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show(_xamlCheckUpdatesFailed.Get());
            }
        }
Beispiel #12
0
    // Excluding most likely unused code from JIT
    private static void KillProcessWithId(string processId)
    {
        var process = Process.GetProcessById(Convert.ToInt32(processId));

        process.Kill();

        ActionWrappers.SleepOnConditionWithTimeout(() => process.HasExited, 1000, 32);
    }
Beispiel #13
0
 private void ChangeToMainPage()
 {
     ActionWrappers.ExecuteWithApplicationDispatcher(() =>
     {
         var viewModel         = IoC.Get <WindowViewModel>();
         viewModel.CurrentPage = Page.Base;
     });
 }
 private void ApplicationLaunched(object sender, EventArrivedEventArgs e)
 {
     ActionWrappers.TryCatchDiscard(() =>
     {
         var processId = Convert.ToInt32(e.NewEvent.Properties[WmiProcessidName].Value);
         var process   = Process.GetProcessById(processId);
         OnNewProcess(process);
     });
 }
Beispiel #15
0
 private void ClientOnReceiveException(GenericExceptionResponse obj)
 {
     ActionWrappers.ExecuteWithApplicationDispatcher(() =>
     {
         var box = new Pages.Dialogs.MessageBox(Errors.Error(), obj.Message);
         box.WindowStartupLocation = WindowStartupLocation.CenterScreen;
         box.ShowDialog();
     });
 }
Beispiel #16
0
        public SplashPage() : base()
        {
            InitializeComponent();

            // Setup ViewModel
            _splashViewModel      = new SplashViewModel();
            this.DataContext      = _splashViewModel;
            _setupApplicationTask = Task.Run(() => Setup.SetupApplicationAsync(UpdateText, _xamlSplashMinimumTime.Get()));
            ActionWrappers.ExecuteWithApplicationDispatcherAsync(Load);
        }
Beispiel #17
0
        private void UpdateReloadedProcesses()
        {
            var result = InstanceTracker.GetProcesses();

            ActionWrappers.ExecuteWithApplicationDispatcher(() =>
            {
                Collections.ModifyObservableCollection(ProcessesWithReloaded, result.ReloadedProcesses);
                Collections.ModifyObservableCollection(ProcessesWithoutReloaded, result.NonReloadedProcesses);
            });
        }
Beispiel #18
0
        /// <summary>
        /// Sets up services which can be used by the various viewmodels.
        /// </summary>
        private static void SetupServices()
        {
            var config = IoC.Get <LoaderConfig>();
            SynchronizationContext synchronizationContext = null;

            ActionWrappers.ExecuteWithApplicationDispatcher(() => synchronizationContext = SynchronizationContext.Current);

            IoC.Kernel.Rebind <IProcessWatcher>().ToConstant(IProcessWatcher.Get());
            IoC.Kernel.Rebind <ApplicationConfigService>().ToConstant(new ApplicationConfigService(config, synchronizationContext));
            IoC.Kernel.Rebind <ModConfigService>().ToConstant(new ModConfigService(config, synchronizationContext));
        }
    /// <summary>
    /// Injects the Reloaded bootstrapper into an active process.
    /// </summary>
    /// <exception cref="ArgumentException">DLL Injection failed, likely due to bad DLL or application.</exception>
    public void Inject()
    {
        long handle = _injector.Inject(GetBootstrapperPath(_process));

        if (handle == 0)
        {
            throw new ArgumentException(Resources.ErrorDllInjectionFailed.Get());
        }

        try
        {
            // Wait until mod loader loads.
            // If debugging, ignore timeout.
            bool WhileCondition()
            {
                if (CheckRemoteDebuggerPresent(_process.Handle, out var isDebuggerPresent))
                {
                    return(isDebuggerPresent);
                }

                return(false);
            }

            ActionWrappers.TryGetValueWhile(() =>
            {
                // Exit if application crashes while loading Reloaded.
                if (_process.HasExited)
                {
                    return(0);
                }

                if (!ReloadedMappedFile.Exists(_process.Id))
                {
                    throw new Exception("Reloaded isn't yet loaded.");
                }

                using var file = new ReloadedMappedFile(_process.Id);
                if (!file.GetState().IsInitialized)
                {
                    throw new Exception("Reloaded is loaded but not fully initalized.");
                }

                return(0);
            }, WhileCondition, _modLoaderSetupTimeout, _modLoaderSetupSleepTime);
        }
        catch (Exception e)
        {
            ActionWrappers.ExecuteWithApplicationDispatcherAsync(() =>
            {
                Errors.HandleException(new Exception(Resources.ErrorFailedToObtainPort.Get(), e));
            });
        };
    }
Beispiel #20
0
    private static void PreloadAddresses()
    {
        // Dummy. Static constructor only needed.
        if (_initialized)
        {
            return;
        }

        ActionWrappers.TryCatch(() => { _x64LoadLibraryAddress = Getx64LoadLibraryAddress(); });
        ActionWrappers.TryCatch(() => { _x86LoadLibraryAddress = Getx86LoadLibraryAddress(); });
        _initialized = true;
    }
Beispiel #21
0
        /// <summary>
        /// Checks for missing mod loader dependencies.
        /// </summary>
        private static void CheckForMissingDependencies()
        {
            var deps = new DependencyChecker(IoC.Get <LoaderConfig>(), IntPtr.Size == 8);

            if (!deps.AllAvailable)
            {
                ActionWrappers.ExecuteWithApplicationDispatcher(() =>
                {
                    var dialog = new MissingCoreDependencyDialog(deps);
                    dialog.ShowDialog();
                });
            }
        }
Beispiel #22
0
    /// <summary>
    /// Checks for missing mod loader dependencies.
    /// </summary>
    private static void CheckForMissingDependencies()
    {
        var deps = new DependencyChecker(IoC.Get <LoaderConfig>(), IntPtr.Size == 8);

        if (deps.AllAvailable)
        {
            return;
        }

        ActionWrappers.ExecuteWithApplicationDispatcher(() =>
        {
            Actions.ShowMissingCoreDependencyDialog(new MissingCoreDependencyDialogViewModel(deps));
        });
    }
Beispiel #23
0
        public async void Refresh()
        {
            try
            {
                var loadedMods = await Task.Run(RefreshTask);

                ActionWrappers.ExecuteWithApplicationDispatcher(() =>
                {
                    Collections.ModifyObservableCollection(CurrentMods, loadedMods.Mods);
                    RaisePropertyChangedEvent(nameof(CurrentMods));
                });
            }
            catch (Exception) { }
        }
Beispiel #24
0
        /// <summary>
        /// Downloads mods in an asynchronous fashion.
        /// </summary>
        public static async Task DownloadPackagesAsync(IEnumerable <string> modIds, bool includePrerelease, bool includeUnlisted, CancellationToken token = default)
        {
            var nugetUtility    = IoC.Get <NugetHelper>();
            var packages        = new List <IPackageSearchMetadata>();
            var missingPackages = new List <string>();

            /* Get details of every mod. */
            foreach (var modId in modIds)
            {
                var packageDetails = await nugetUtility.GetPackageDetails(modId, includePrerelease, includeUnlisted, token);

                if (packageDetails.Any())
                {
                    packages.Add(packageDetails.Last());
                }
                else
                {
                    missingPackages.Add(modId);
                }
            }

            /* Get dependencies of every mod. */
            foreach (var package in packages.ToArray())
            {
                var dependencies = await nugetUtility.FindDependencies(package, includePrerelease, includeUnlisted, token);

                packages.AddRange(dependencies.Dependencies);
                missingPackages.AddRange(dependencies.PackagesNotFound);
            }

            /* Remove already existing packages. */
            var allMods = IoC.Get <ManageModsViewModel>().Mods.ToArray();
            HashSet <string> allModIds = new HashSet <string>(allMods.Length);

            foreach (var mod in allMods)
            {
                allModIds.Add(mod.ModConfig.ModId);
            }

            // Remove mods we already have.
            packages        = packages.Where(x => !allModIds.Contains(x.Identity.Id)).ToList();
            missingPackages = missingPackages.Where(x => !allModIds.Contains(x)).ToList();

            ActionWrappers.ExecuteWithApplicationDispatcher(() =>
            {
                var dialog = new NugetFetchPackageDialog(packages, missingPackages);
                dialog.ShowDialog();
            });
        }
Beispiel #25
0
    /// <summary>
    /// Resolves a list of missing packages.
    /// </summary>
    /// <param name="token">Used to cancel the operation.</param>
    public static async Task ResolveMissingPackagesAsync(CancellationToken token = default)
    {
        if (!HasInternetConnection)
        {
            return;
        }

        ModDependencyResolveResult resolveResult = null !;

        do
        {
            // Get missing dependencies for this update loop.
            var missingDeps = CheckMissingDependencies();

            // Get Dependencies
            var resolver = DependencyResolverFactory.GetInstance(IoC.Get <AggregateNugetRepository>());

            var results = new List <Task <ModDependencyResolveResult> >();
            foreach (var dependencyItem in missingDeps.Items)
            {
                foreach (var dependency in dependencyItem.Dependencies)
                {
                    results.Add(resolver.ResolveAsync(dependency, dependencyItem.Mod.PluginData, token));
                }
            }

            await Task.WhenAll(results);

            // Merge Results
            resolveResult = ModDependencyResolveResult.Combine(results.Select(x => x.Result));
            DownloadPackages(resolveResult, token);
        }while (resolveResult.FoundDependencies.Count > 0);

        if (resolveResult.NotFoundDependencies.Count > 0)
        {
            ActionWrappers.ExecuteWithApplicationDispatcher(() =>
            {
                Actions.DisplayMessagebox(Resources.ErrorMissingDependency.Get(),
                                          $"{Resources.FetchNugetNotFoundMessage.Get()}\n\n" +
                                          $"{string.Join('\n', resolveResult.NotFoundDependencies)}\n\n" +
                                          $"{Resources.FetchNugetNotFoundAdvice.Get()}",
                                          new Actions.DisplayMessageBoxParams()
                {
                    Type            = Actions.MessageBoxType.Ok,
                    StartupLocation = Actions.WindowStartupLocation.CenterScreen
                });
            });
        }
    }
Beispiel #26
0
 /// <summary>
 /// Handles a generic thrown exception.
 /// </summary>
 public static void HandleException(Exception ex, string message = "")
 {
     if (!Debugger.IsAttached)
     {
         ActionWrappers.ExecuteWithApplicationDispatcher(() =>
         {
             var messageBox = new MessageBox(Errors.UnknownError(), $"{message}{ex.Message}\n{ex.StackTrace}");
             messageBox.ShowDialog();
         });
     }
     else
     {
         Debugger.Break();
     }
 }
Beispiel #27
0
    public FirstLaunch()
    {
        InitializeComponent();

        ViewModel = Lib.IoC.Get <FirstLaunchViewModel>();

        // Disable Original Button Visibility
        base.ViewModel.CloseButtonVisibility    = Visibility.Collapsed;
        base.ViewModel.MaximizeButtonVisibility = Visibility.Collapsed;
        base.ViewModel.MinimizeButtonVisibility = Visibility.Collapsed;

        // Init Events
        ViewModel.Initialize(() => ActionWrappers.ExecuteWithApplicationDispatcher(this.Close));
        this.Closing += (sender, args) => ViewModel.Dispose();
    }
    private void UpdateReloadedProcesses()
    {
        var result = _instanceTracker.GetProcesses(_initialiseTokenSrc.Token);

        ActionWrappers.ExecuteWithApplicationDispatcherAsync(() =>
        {
            if (_initialiseTokenSrc.IsCancellationRequested)
            {
                return;
            }

            Collections.ModifyObservableCollection(ProcessesWithReloaded, result.ReloadedProcesses);
            Collections.ModifyObservableCollection(ProcessesWithoutReloaded, result.NonReloadedProcesses);
        });
    }
Beispiel #29
0
 private void DisplayFirstLaunchWarningIfNeeded()
 {
     ActionWrappers.ExecuteWithApplicationDispatcher(() =>
     {
         var loaderConfig = IoC.Get <LoaderConfig>();
         if (loaderConfig.FirstLaunch)
         {
             var firstLaunchWindow   = new FirstLaunch();
             firstLaunchWindow.Owner = Window.GetWindow(this);
             firstLaunchWindow.ShowDialog();
             loaderConfig.FirstLaunch = false;
             LoaderConfigReader.WriteConfiguration(loaderConfig);
         }
     });
 }
Beispiel #30
0
        /// <summary>
        /// Cleans up files/folders after upgrades from old loader versions.
        /// </summary>
        private static void CleanupAfterOldVersions()
        {
            var launcherFolder = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);

            DestroyFolder(launcherFolder, "Languages");
            DestroyFolder(launcherFolder, "Styles");
            DestroyFolder(launcherFolder, "Templates");

            #if !DEBUG
            DestroyFileType(launcherFolder, "*.pdb");
            DestroyFileType(launcherFolder, "*.xml");
            #endif

            // Check for .NET 5 Single File
            // This code is unused until .NET 5 upgrade.
            if (Environment.Version >= Version.Parse("5.0.0"))
            {
                // Currently no API to check if in bundle (single file app); however, we know that CodeBase returns true when loaded from memory.
                var resAsm        = Application.ResourceAssembly;
                var configuration = resAsm.GetCustomAttribute <AssemblyConfigurationAttribute>();
                if (configuration != null && configuration.Configuration.Contains("SingleFile"))
                {
                    // TODO: Needs more testing. Seems to work but might be problematic.
                    DestroyFileType(launcherFolder, "*.json");
                    DestroyFileType(launcherFolder, "*.dll");
                }
            }

            void DestroyFolder(string baseFolder, string folderName)
            {
                var folderPath = Path.Combine(baseFolder, folderName);

                ActionWrappers.TryCatchDiscard(() => Directory.Delete(folderPath, true));
            }

            void DestroyFileType(string baseFolder, string searchPattern)
            {
                var files = Directory.GetFiles(baseFolder, searchPattern);

                foreach (var file in files)
                {
                    ActionWrappers.TryCatchDiscard(() => File.Delete(file));
                }
            }
        }