예제 #1
0
 private void UpdatePreviewImage()
 {
     if (!_finished)
     {
         _waiting?.SetImage(Path.Combine(_currentSkin.Location, _options.PreviewName));
     }
 }
예제 #2
0
            private async Task <IReadOnlyList <UpdatePreviewError> > RunReady()
            {
                _checksum = _options.GetChecksum();
                Logging.Debug(_checksum);

                _finished = false;
                _i        = _j = 0;

                _waiting = Progress != null ? null : new WaitingDialog {
                    CancellationText = "Stop"
                };
                var progressReport = Progress ?? _waiting;

                if (Progress == null)
                {
                    CancellationToken = _waiting?.CancellationToken ?? default(CancellationToken);
                }

                var singleMode = _entries.Count == 1;

                _verySingleMode = singleMode && _entries[0].Skins?.Count == 1;
                var recycled = 0;

                if (!_verySingleMode)
                {
                    _waiting?.SetImage(null);

                    if (SettingsHolder.CustomShowroom.PreviewsRecycleOld)
                    {
                        _waiting?.SetMultiline(true);
                    }
                }

                var step    = 1d / _entries.Count;
                var postfix = string.Empty;

                _started = Stopwatch.StartNew();

                _dispatcherTimer = new DispatcherTimer(TimeSpan.FromSeconds(0.5), DispatcherPriority.Background, TimerCallback,
                                                       Application.Current?.Dispatcher ?? Dispatcher.CurrentDispatcher);
                _dispatcherTimer.Start();

                for (_j = 0; _j < _entries.Count; _j++)
                {
                    if (Cancel())
                    {
                        return(_errors);
                    }

                    var entry    = _entries[_j];
                    var progress = step * _j;

                    _currentCar   = entry.Car;
                    _currentSkins = entry.Skins;

                    if (_currentSkins == null)
                    {
                        progressReport?.Report(new AsyncProgressEntry("Loading skins…" + postfix, _verySingleMode ? 0d : progress));
                        _waiting?.SetDetails(GetDetails(_j, _currentCar, null, null));

                        await _currentCar.SkinsManager.EnsureLoadedAsync();

                        if (Cancel())
                        {
                            return(_errors);
                        }

                        _currentSkins = _currentCar.EnabledOnlySkins.ToList();
                        UpdateApproximate(_currentSkins.Count);
                    }

                    var halfstep = step * 0.5 / _currentSkins.Count;
                    for (_i = 0; _i < _currentSkins.Count; _i++)
                    {
                        if (Cancel())
                        {
                            return(_errors);
                        }

                        _currentSkin = _currentSkins[_i];
                        _waiting?.SetDetails(GetDetails(_j, _currentCar, _currentSkin, _currentSkins.Count - _i));

                        var subprogress = progress + step * (0.1 + 0.8 * _i / _currentSkins.Count);
                        var filename    = DestinationOverrideCallback?.Invoke(_currentSkin) ?? Path.Combine(_currentSkin.Location, _options.PreviewName);
                        if (DestinationOverrideCallback == null)
                        {
                            if (SettingsHolder.CustomShowroom.PreviewsRecycleOld && File.Exists(filename))
                            {
                                if (++recycled > 5)
                                {
                                    _recyclingWarning = true;
                                }

                                progressReport?.Report(new AsyncProgressEntry($"Recycling current preview for {_currentSkin.DisplayName}…" + postfix,
                                                                              _verySingleMode ? 0d : subprogress));
                                await Task.Run(() => FileUtils.Recycle(filename));
                            }
                        }

                        progressReport?.Report(new AsyncProgressEntry($"Updating skin {_currentSkin.DisplayName}…" + postfix,
                                                                      _verySingleMode ? 0d : subprogress + halfstep));

                        try {
                            await _updater.ShotAsync(_currentCar.Id, _currentSkin.Id, filename, _currentCar.AcdData,
                                                     GetInformation(_currentCar, _currentSkin, _presetName, _checksum), PreviewReadyCallback);

                            _shotSkins++;
                        } catch (Exception e) {
                            if (_errors.All(x => x.ToUpdate != entry))
                            {
                                Logging.Warning(e);
                                _errors.Add(new UpdatePreviewError(entry, e.Message, null));
                            }
                        }
                    }
                }

                _dispatcherTimer?.Stop();
                progressReport?.Report(new AsyncProgressEntry("Saving…" + postfix, _verySingleMode ? 0d : 0.999999d));
                await _updater.WaitForProcessing();

                _finished = true;

                if (_errors.Count > 0)
                {
                    NonfatalError.Notify("Can’t update previews:\n"
                                         + _errors.Select(x => @"• " + x.Message.ToSentence()).JoinToString(";" + Environment.NewLine));
                }

                return(_errors);
            }
예제 #3
0
        private static async Task <IReadOnlyList <UpdatePreviewError> > UpdatePreview(IReadOnlyList <ToUpdatePreview> entries, DarkPreviewsOptions options, string presetName = null,
                                                                                      DarkPreviewsUpdater updater = null)
        {
            var localUpdater = updater == null;

            if (localUpdater)
            {
                updater = new DarkPreviewsUpdater(AcRootDirectory.Instance.RequireValue, options);
            }
            else
            {
                updater.SetOptions(options);
            }

            var errors = new List <UpdatePreviewError>();

            try {
                if (options.Showroom != null && ShowroomsManager.Instance.GetById(options.Showroom) == null)
                {
                    if (options.Showroom == "at_previews" && MissingShowroomHelper != null)
                    {
                        await MissingShowroomHelper.OfferToInstall("Kunos Previews Showroom (AT Previews Special)", "at_previews",
                                                                   "http://www.assettocorsa.net/assetto-corsa-v1-5-dev-diary-part-33/");

                        if (ShowroomsManager.Instance.GetById(options.Showroom) != null)
                        {
                            goto Action;
                        }
                    }

                    throw new InformativeException("Can’t update preview", $"Showroom “{options.Showroom}” is missing");
                }

Action:
                var checksum = options.GetChecksum();

                var finished = false;
                var j        = 0;

                using (var waiting = new WaitingDialog()) {
                    var cancellation = waiting.CancellationToken;

                    var singleMode     = entries.Count == 1;
                    var verySingleMode = singleMode && entries[0].Skins?.Count == 1;
                    var recycled       = 0;

                    if (!verySingleMode)
                    {
                        waiting.SetImage(null);

                        if (SettingsHolder.CustomShowroom.PreviewsRecycleOld)
                        {
                            waiting.SetMultiline(true);
                        }
                    }

                    var step    = 1d / entries.Count;
                    var postfix = string.Empty;

                    var started = Stopwatch.StartNew();
                    var approximateSkinsPerCarCars  = 1;
                    var approximateSkinsPerCarSkins = 10;

                    Action <int> updateApproximate = skinsPerCar => {
                        approximateSkinsPerCarCars++;
                        approximateSkinsPerCarSkins += skinsPerCar;
                    };

                    Func <int, int> leftSkins = currentEntry => {
                        var skinsPerCar = (double)approximateSkinsPerCarSkins / approximateSkinsPerCarCars;

                        var result = 0d;
                        for (var k = currentEntry; k < entries.Count; k++)
                        {
                            var entry = entries[k];
                            result += entry.Skins?.Count ?? skinsPerCar;
                        }

                        return(result.RoundToInt());
                    };

                    var shotSkins        = 0;
                    var recyclingWarning = false;
                    Func <CarObject, CarSkinObject, int?, IEnumerable <string> > getDetails = (car, skin, currentEntrySkinsLeft) => {
                        var left = leftSkins(j) + (currentEntrySkinsLeft ?? approximateSkinsPerCarSkins / approximateSkinsPerCarCars);

                        // ReSharper disable once AccessToModifiedClosure
                        var speed          = shotSkins / started.Elapsed.TotalMinutes;
                        var remainingTime  = speed < 0.0001 ? "Unknown" : $"About {TimeSpan.FromMinutes(left / speed).ToReadableTime()}";
                        var remainingItems = $"About {left} {PluralizingConverter.Pluralize(left, ControlsStrings.CustomShowroom_SkinHeader).ToSentenceMember()}";

                        return(new[] {
                            $"Car: {car?.DisplayName}",
                            $"Skin: {skin?.DisplayName ?? "?"}",
                            $"Speed: {speed:F2} {PluralizingConverter.Pluralize(10, ControlsStrings.CustomShowroom_SkinHeader).ToSentenceMember()}/{"min"}",
                            $"Time remaining: {remainingTime}",
                            $"Items remaining: {remainingItems}",

                            // ReSharper disable once AccessToModifiedClosure
                            recyclingWarning ? "[i]Recycling seems to take too long? If so, it can always be disabled in Settings.[/i]" : null
                        }.NonNull());
                    };

                    for (j = 0; j < entries.Count; j++)
                    {
                        if (cancellation.IsCancellationRequested)
                        {
                            goto Cancel;
                        }

                        var entry    = entries[j];
                        var progress = step * j;

                        var car   = entry.Car;
                        var skins = entry.Skins;

                        if (skins == null)
                        {
                            waiting.Report(new AsyncProgressEntry("Loading skins…" + postfix, verySingleMode ? 0d : progress));
                            waiting.SetDetails(getDetails(car, null, null));

                            await car.SkinsManager.EnsureLoadedAsync();

                            if (cancellation.IsCancellationRequested)
                            {
                                goto Cancel;
                            }

                            skins = car.EnabledOnlySkins.ToList();
                            updateApproximate(skins.Count);
                        }

                        var halfstep = step * 0.5 / skins.Count;
                        for (var i = 0; i < skins.Count; i++)
                        {
                            if (cancellation.IsCancellationRequested)
                            {
                                goto Cancel;
                            }

                            var skin = skins[i];
                            waiting.SetDetails(getDetails(car, skin, skins.Count - i));

                            var subprogress = progress + step * (0.1 + 0.8 * i / skins.Count);
                            if (SettingsHolder.CustomShowroom.PreviewsRecycleOld && File.Exists(skin.PreviewImage))
                            {
                                if (++recycled > 5)
                                {
                                    recyclingWarning = true;
                                }

                                waiting.Report(new AsyncProgressEntry($"Recycling current preview for {skin.DisplayName}…" + postfix, verySingleMode ? 0d : subprogress));
                                await Task.Run(() => FileUtils.Recycle(skin.PreviewImage));
                            }

                            waiting.Report(new AsyncProgressEntry($"Updating skin {skin.DisplayName}…" + postfix, verySingleMode ? 0d : subprogress + halfstep));

                            try {
                                await updater.ShotAsync(car.Id, skin.Id, skin.PreviewImage, car.AcdData, GetInformation(car, skin, presetName, checksum),
                                                        () => {
                                    if (!verySingleMode)
                                    {
                                        ActionExtension.InvokeInMainThreadAsync(() => {
                                            // ReSharper disable once AccessToModifiedClosure
                                            if (!finished)
                                            {
                                                // ReSharper disable once AccessToDisposedClosure
                                                waiting.SetImage(skin.PreviewImage);
                                            }
                                        });
                                    }
                                });

                                shotSkins++;
                            } catch (Exception e) {
                                if (errors.All(x => x.ToUpdate != entry))
                                {
                                    errors.Add(new UpdatePreviewError(entry, e.Message, null));
                                }
                            }
                        }
                    }

                    waiting.Report(new AsyncProgressEntry("Saving…" + postfix, verySingleMode ? 0d : 0.999999d));
                    await updater.WaitForProcessing();

                    finished = true;
                }

                if (errors.Count > 0)
                {
                    NonfatalError.Notify("Can’t update previews:\n" + errors.Select(x => @"• " + x.Message.ToSentence()).JoinToString(";" + Environment.NewLine));
                }

                goto End;

Cancel:
                for (; j < entries.Count; j++)
                {
                    errors.Add(new UpdatePreviewError(entries[j], ControlsStrings.Common_Cancelled, null));
                }

End:
                return(errors);
            } catch (Exception e) {
                NonfatalError.Notify("Can’t update preview", e);
                return(null);
            } finally {
                if (localUpdater)
                {
                    updater.Dispose();
                    GC.Collect();
                }
            }
        }