Ejemplo n.º 1
0
 public Registered(WeakReference <IWebBrowser> webBrowser, string[] allowedHosts, Func <string, string> callback)
 {
     WebBrowser   = webBrowser;
     AllowedHosts = allowedHosts;
     Callback     = callback;
     Identifier   = Lazier.Create(() => WebBrowser.TryGetTarget(out var targetBrowser) ? targetBrowser.GetBrowser().Identifier : -1);
 }
Ejemplo n.º 2
0
 public ImageInformation(ImageViewerImageCallback imageCallback, ImageViewerDetailsCallback detailsCallback, int position)
 {
     _imageCallback   = imageCallback;
     _detailsCallback = detailsCallback;
     _position        = position;
     _details         = Lazier.Create(GetDetails);
 }
Ejemplo n.º 3
0
 public ToolLink()
 {
     _notAvailableReasonValue = Lazier.Create(() => {
         var list = NotAvailableReasonFunc?.Invoke().ToList();
         return(list?.Count > 1 ? list.Select(x => "• " + x).JoinToString(";\n").ToSentence() : list?.Count > 0 ? list[0] : null);
     });
 }
Ejemplo n.º 4
0
 public Emoji([NotNull] string id, [NotNull] IEmojiLoader loader, [NotNull] IEmojiInformationProvider informationProvider)
 {
     _id         = id;
     _loader     = loader;
     Image       = Lazier.Create(LoadImageSource);
     Information = informationProvider.GetInformation(_id);
 }
Ejemplo n.º 5
0
        public WrapperContentObject(AcCommonObject acObject, string contentDirectory)
        {
            _contentDirectory = contentDirectory;
            CanBePacked       = acObject.CanBePacked();

            AcObject = acObject;
            Version  = ContentVersion = (acObject as IAcObjectVersionInformation)?.Version;

            AcObject.SubscribeWeak((sender, args) => {
                switch (args.PropertyName)
                {
                case nameof(AcCommonObject.DisplayName):
                    UpdateDisplayName();
                    break;

                case nameof(IAcObjectVersionInformation.Version):
                    var updated = (acObject as IAcObjectVersionInformation)?.Version;
                    if (Version == ContentVersion)
                    {
                        Version = updated;
                    }

                    ContentVersion = updated;
                    break;
                }
            });

            UpdateDisplayName();
            _sizeLazy          = Lazier.Create(GetSize);
            _fileIsMissingLazy = Lazier.Create(() => ShareMode == ShareMode.Directly && Filename != null && !File.Exists(Filename));
        }
Ejemplo n.º 6
0
        static PatchHelper()
        {
            _installed = Lazier.Create(() => {
                var installedLogFilename = GetInstalledLog();
                if (!File.Exists(installedLogFilename))
                {
                    return(Tuple.Create <string, string>(null, null));
                }

                string version = null, build = null;
                foreach (var line in File.ReadAllLines(installedLogFilename).Select(x => x.Trim()).Where(x => !x.StartsWith(@"#")))
                {
                    var keyValue = line.Split(new[] { ':' }, 2, StringSplitOptions.None);
                    if (keyValue.Length != 2)
                    {
                        continue;
                    }
                    switch (keyValue[0].Trim())
                    {
                    case "version":
                        version = keyValue[1].Trim();
                        break;

                    case "build":
                        build = keyValue[1].Trim();
                        break;
                    }
                }

                return(Tuple.Create(version, build));
            });
        }
Ejemplo n.º 7
0
 private void UnloadDriverModel()
 {
     Remove(_driver);
     DisposeHelper.Dispose(ref _driver);
     _driverSteerAnimator = null;
     ObjectsChanged?.Invoke(this, EventArgs.Empty);
 }
Ejemplo n.º 8
0
 public SettingValue(string name, string value, ZipArchiveEntry entry, double performanceHitMs, bool isActive)
 {
     DisplayName = name.ToSentenceMember();
     Data        = Lazier.Create(() => entry.Open().ReadAsBytesAndDispose());
     Value       = value;
     PerformanceHitPercentage = performanceHitMs / 12 * 100;
     IsActive = isActive;
 }
Ejemplo n.º 9
0
        public BuiltInPresetEntry([NotNull] string baseDirectory, [NotNull] string filename, [NotNull] string extension, byte[] data)
        {
            _extension      = extension;
            _baseDirectory  = baseDirectory;
            _data           = data;
            VirtualFilename = filename;

            _displayName = Lazier.Create(GetDisplayName);
        }
Ejemplo n.º 10
0
        private void LoadDriverModel()
        {
            if (_driver != null)
            {
                return;
            }

            var driverDescription = _carData.GetDriverDescription();

            if (driverDescription == null || !File.Exists(_driverModelFilename))
            {
                return;
            }

            var driver = new Kn5RenderableDriver(Kn5.FromFile(_driverModelFilename), Matrix.Translation(driverDescription.Offset),
                                                 _currentSkin == null ? null : Path.Combine(_skinsDirectory, _currentSkin),
                                                 AsyncTexturesLoading, _asyncOverrideTexturesLoading, _converter)
            {
                LiveReload     = LiveReload,
                MagickOverride = MagickOverride
            };

            _driver = driver;

            if (File.Exists(_driverHierarchyFilename))
            {
                driver.AlignNodes(Knh.FromFile(_driverHierarchyFilename));
            }

            _driverSteerAnimator = Lazier.Create(() => {
                var animator = CreateAnimator(RootDirectory, driverDescription.SteerAnimation,
                                              clampEnabled: false, skipFixed: false);
                if (animator == null)
                {
                    return(null);
                }

                animator.Reset += OnSteerAnimatorReset;
                return(animator);
            });
            _driverSteerLock = driverDescription.SteerAnimationLock;

            driver.LocalMatrix = RootObject.LocalMatrix;
            Add(driver);
            ObjectsChanged?.Invoke(this, EventArgs.Empty);

            if (_steerDeg != 0 || OptionFixKnh)
            {
                UpdateDriverSteerAnimation(GetSteerOffset());
            }

            if (DebugMode)
            {
                driver.DebugMode = true;
            }
        }
Ejemplo n.º 11
0
        public SavedPresetEntry(string baseDirectory, string extension, string filename)
        {
            _baseDirectory        = baseDirectory;
            _displayBaseDirectory = baseDirectory;
            _extension            = extension;
            VirtualFilename       = filename;

            _displayName      = Lazier.Create(GetDisplayName);
            _shortDisplayName = Lazier.Create(GetShortDisplayName);
        }
Ejemplo n.º 12
0
 internal GenericMod(GenericModsEnabler enabler, string modDirectory)
 {
     _enabler     = enabler;
     DisplayName  = Path.GetFileName(modDirectory);
     ModDirectory = modDirectory;
     Description  = new Lazier <string>(() => Task.Run(() => {
         var d = Directory.GetFiles(ModDirectory, "*" + DescriptionExtension, SearchOption.TopDirectoryOnly);
         return(d.Length > 0 ? File.ReadAllText(d[0]) : null);
     }));
 }
Ejemplo n.º 13
0
 public MostUsedTrack(int index, [NotNull] string acObjectId, double totalValue, string displayValue, IEnumerable <MostUsedTrackLayout> layouts)
     : base(index, acObjectId, totalValue, displayValue)
 {
     Track   = Lazier.CreateAsync(() => TracksManager.Instance.GetByIdAsync(AcObjectId));
     Layouts = layouts.ToList();
     if (Layouts.Count == 1)
     {
         Layouts.Clear();
     }
 }
Ejemplo n.º 14
0
 public static void Dispose <T>([CanBeNull] ref Lazier <T> disposable) where T : class, IDisposable
 {
     if (disposable == null)
     {
         return;
     }
     if (disposable.IsSet)
     {
         disposable.Value?.Dispose();
         disposable.Reset();
     }
 }
Ejemplo n.º 15
0
        public async Task TestAsync()
        {
            var i = 0;
            var l = Lazier.CreateAsync(async() => {
                var v = ++i;
                await Task.Delay(25);
                return(v);
            }, -1);

            Assert.IsFalse(l.IsSet);
            Assert.AreEqual(-1, l.Value);
            Assert.AreEqual(1, i);
            Assert.IsFalse(l.IsSet);
            await Task.Delay(1);

            Assert.AreEqual(1, i);
            Assert.AreEqual(-1, l.Value);
            Assert.IsFalse(l.IsSet);
            await Task.Delay(50);

            Assert.AreEqual(1, l.Value);
            Assert.IsTrue(l.IsSet);
            Assert.AreEqual(1, l.Value);
            l.Reset();



            Assert.IsFalse(l.IsSet);
            Assert.AreEqual(-1, l.Value);
            Assert.AreEqual(2, i);
            await Task.Delay(50);

            Assert.AreEqual(2, l.Value);
            Assert.IsTrue(l.IsSet);
            Assert.AreEqual(2, l.Value);
            l.Reset();


            Assert.AreEqual(-1, l.Value);
            Assert.AreEqual(3, i);
            await Task.Delay(15);

            l.Reset();
            Assert.AreEqual(-1, l.Value);
            Assert.AreEqual(4, i);
            await Task.Delay(50);

            Assert.AreEqual(4, l.Value);

            l.Reset();
            Assert.AreEqual(5, l.GetValueAsync().Result);
        }
Ejemplo n.º 16
0
        public ServerEntry([NotNull] ServerInformation information)
        {
            if (information == null)
            {
                throw new ArgumentNullException(nameof(information));
            }
            _sortingName = Lazier.Create(() => GetSortingName(DisplayName));

            Id       = information.Id;
            Ip       = information.Ip;
            PortHttp = information.PortHttp;
            Ping     = null;
            UpdateValuesAsync(information, true).Ignore();
        }
Ejemplo n.º 17
0
        static AcShadowsPatcher()
        {
            SupportedVersions = Lazier.Create(() => {
                var x86   = _data?.For32BitVersion?.Where(x => x.Value.Original != null).Select(x => x.Key).JoinToReadableString();
                var x64   = _data?.For64BitVersion?.Where(x => x.Value.Original != null).Select(x => x.Key).JoinToReadableString();
                var items = new[] {
                    string.IsNullOrWhiteSpace(x86) ? null : "32-bit: " + x86,
                    string.IsNullOrWhiteSpace(x64) ? null : "64-bit: " + x64,
                }.NonNull().ToArray();
                return(items.Length == 0 ? "Definitions are missing" : items.JoinToString(Environment.NewLine));
            });

            ReloadData(true);
            FilesStorage.Instance.Watcher(ContentCategory.Miscellaneous).Update += (s, a) => ReloadData(false);
        }
Ejemplo n.º 18
0
        private DataProvider()
        {
            FilesStorage.Instance.Watcher(ContentCategory.Miscellaneous).Update += OnUpdate;

            _nameNationalities = Lazier.Create(() => NationalitiesAndNames.SelectMany(
                                                   x => from y in x.Value select new NameNationality {
                Name = y, Nationality = x.Key
            }).ToList());

            _countryToIds      = Lazier.Create <IReadOnlyDictionary <string, string> >(() => CountryByIds.ToDictionary(x => x.Value, x => x.Key));
            _countryToKunosIds = Lazier.Create <IReadOnlyDictionary <string, string> >(() => CountryByKunosIds.ToDictionary(x => x.Value, x => x.Key));

            _carYears      = Lazier.Create <IReadOnlyDictionary <string, int> >(() => Years.GetValueOrDefault("cars") ?? new Dictionary <string, int>());
            _trackYears    = Lazier.Create <IReadOnlyDictionary <string, int> >(() => Years.GetValueOrDefault("tracks") ?? new Dictionary <string, int>());
            _showroomYears = Lazier.Create <IReadOnlyDictionary <string, int> >(() => Years.GetValueOrDefault("showrooms") ?? new Dictionary <string, int>());
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="InventoryItem"/> class.
        /// </summary>
        /// <param name="itemKey">Unique identifier of the item to wrap.</param>
        /// <param name="defaultPreUseSleep">Default number of milliseconds to wait before using the item.</param>
        /// <param name="defaultPostUseSleep">Default number of milliseconds to wait after using the item.</param>
        /// <param name="defaultMaxTimeout">Default timeout for item action to execute.</param>
        /// <param name="defaultMountBehavior">Default mount behavior. Set to true if player should dismount when
        /// using the item action.</param>
        public InventoryItem(InventoryItemKey itemKey, int defaultPreUseSleep = 500, int defaultPostUseSleep = 1500, TimeSpan?defaultMaxTimeout = null, bool defaultMountBehavior = false)
        {
            if (itemKey == null || itemKey.Id == 0)
            {
                throw new ArgumentException("InventoryItem(itemId) must be defined with an Id greater than 0.");
            }

            this.itemKey              = itemKey;
            this.defaultMaxTimeout    = defaultMaxTimeout ?? new TimeSpan(0, 0, 0, DEFAULT_TIMEOUT_SECONDS);
            this.defaultMountBehavior = defaultMountBehavior;
            this.defaultPreUseSleep   = defaultPreUseSleep;
            this.defaultPostUseSleep  = defaultPostUseSleep;

            this.itemData  = new Lazier <Item>(GetItem, LazyThreadSafetyMode.ExecutionAndPublication, true);
            this.spellData = new Lazier <SpellData>(GetBackingAction, LazyThreadSafetyMode.ExecutionAndPublication, true);
        }
Ejemplo n.º 20
0
            public RaceResultsObject(FileInfo fileInfo)
            {
                Filename      = fileInfo.FullName;
                CreationTime  = fileInfo.CreationTime;
                LastWriteTime = fileInfo.LastWriteTime;
                Size          = fileInfo.Length;
                DisplayName   = fileInfo.Name;

                PlayerCar = Lazier.CreateAsync(() => CarsManager.Instance.GetByIdAsync(Parsed?.Players?.FirstOrDefault()?.CarId ?? ""));
                Cars      = Lazier.CreateAsync(async() => (await(Parsed?.Players?.Select(x => x.CarId)
                                                                 .Distinct()
                                                                 .Select(x => CarsManager.Instance.GetByIdAsync(x ?? ""))
                                                                 .WhenAll() ??
                                                                 Task.FromResult <IEnumerable <CarObject> >(null)).ConfigureAwait(false)).Select((x, y) => new WrappedCarObject(x, y == 0))
                                               .OrderBy(x => x.Car.DisplayName).ToList());
                ModeDetails = Lazier.CreateAsync(GetModeDetails);
            }
Ejemplo n.º 21
0
        public void TestBasic()
        {
            var i = 0;
            var l = Lazier.Create(() => ++ i);

            Assert.IsFalse(l.IsSet);
            Assert.AreEqual(1, l.Value);
            Assert.IsTrue(l.IsSet);
            Assert.AreEqual(1, l.Value);
            l.Reset();
            Assert.IsFalse(l.IsSet);
            Assert.AreEqual(2, l.Value);
            Assert.IsTrue(l.IsSet);
            Assert.AreEqual(2, l.Value);
            l.Reset();
            Assert.AreEqual(3, l.Value);
        }
Ejemplo n.º 22
0
        public async Task <string> GetSoundOrigin()
        {
            if (_soundDonorSet)
            {
                return(_soundDonorId);
            }
            _soundDonorSet = true;

            try {
                if (_kunosGuids == null)
                {
                    await ReadKunosGuidsAsync().ConfigureAwait(false);

                    if (_kunosGuids == null)
                    {
                        return(null);
                    }
                }

                if (!File.Exists(GuidsFilename))
                {
                    // TODO
                    return(null);
                }

                var lines = await FileUtils.ReadAllLinesAsync(GuidsFilename).ConfigureAwait(false);

                foreach (var line in lines)
                {
                    var m = _guidsRegex.Match(line);
                    if (m.Success && m.Groups[2].Value == Id && _kunosGuids.TryGetValue(m.Groups[1].Value, out _soundDonorId))
                    {
                        _soundDonor = new Lazier <CarObject>(() => SoundDonorId == null ? null : CarsManager.Instance.GetById(SoundDonorId));
                        OnPropertyChanged(nameof(SoundDonorId));
                        OnPropertyChanged(nameof(SoundDonor));
                        return(_soundDonorId);
                    }
                }

                return(null);
            } catch (Exception e) {
                Logging.Error(e);
                return(null);
            }
        }
Ejemplo n.º 23
0
            public WeatherProceduralContext(IniFile raceIni, string weatherLocation)
            {
                _raceIni           = raceIni;
                RaceIni            = new LuaIniFile(raceIni);
                TrackId            = $@"{raceIni["RACE"].GetNonEmpty("TRACK")}/{raceIni["RACE"].GetNonEmpty("CONFIG_TRACK")}".TrimEnd('/');
                _weatherIni        = Lazier.Create(() => new LuaIniFile(Path.Combine(weatherLocation, "weather.ini")));
                _colorCurvesIni    = Lazier.Create(() => new LuaIniFile(Path.Combine(weatherLocation, "colorCurves.ini")));
                _weatherFilterIni  = Lazier.Create(() => new LuaIniFile(Path.Combine(weatherLocation, "filter.ini")));
                _tyreSmokeIni      = Lazier.Create(() => new LuaIniFile(Path.Combine(weatherLocation, "tyre_smoke.ini")));
                _tyreSmokeGrassIni = Lazier.Create(() => new LuaIniFile(Path.Combine(weatherLocation, "tyre_smoke_grass.ini")));
                _userFilterIni     = Lazier.Create(() => new LuaIniFile(PpFiltersManager.Instance.GetByAcId(AcSettingsHolder.Video.PostProcessingFilter)?.Location));

                // BUG: USE BACKUPED VALUES IF ANY INSTEAD!
                _trackLightingIni = Lazier.Create(() => new LuaIniFile(Path.Combine(Track.DataDirectory, "lighting.ini")));

                _track            = Lazier.Create(() => TracksManager.Instance.GetLayoutById(TrackId));
                _activeTrackSkins = Lazier.Create(() => Track.MainTrackObject.EnabledOnlySkins.Where(x => x.IsActive).ToList());
            }
Ejemplo n.º 24
0
        public ServerEntry([NotNull] ServerInformation information)
        {
            if (information == null)
            {
                throw new ArgumentNullException(nameof(information));
            }
            _sortingName = Lazier.Create(() => GetSortingName(DisplayName));

            Id       = information.Id;
            Ip       = information.Ip;
            PortHttp = information.PortHttp;
            Ping     = null;

            PrepareErrorsList();
            var status = UpdateValues(information, true, true);

            Status = status == ServerStatus.MissingContent ? ServerStatus.Unloaded : status ?? ServerStatus.Unloaded;
            UpdateErrorsList();
        }
Ejemplo n.º 25
0
            public ColorReference GetColorReference([NotNull] string ruleId, int colorIndex)
            {
                ColorReference result = null;
                var            source = new Lazier <AspectsPaintableItem>(() => {
                    var sourceFound = GetSource(ruleId) as AspectsPaintableItem;
                    if (sourceFound != null)
                    {
                        sourceFound.ColorChanged += (sender, args) => {
                            if (args.ColorIndex == null || args.ColorIndex == colorIndex)
                            {
                                result?.RaiseUpdated();
                            }
                        };
                    }

                    return(sourceFound);
                });

                result = new ColorReference(() => source.Value?.GetColor(colorIndex)?.ToColor(255));
                return(result);
            }
Ejemplo n.º 26
0
        protected static IEnumerable <IKn5RenderableObject> Flatten(Kn5 kn5, IEnumerable <IRenderableObject> root, [CanBeNull] string textureName,
                                                                    [CanBeNull] string objectPath)
        {
            var split = Lazier.Create(() => objectPath?.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries));

            bool TestObjectPath(IKn5RenderableObject obj)
            {
                var s = split.Value;

                if (s == null || s.Length < 1)
                {
                    return(true);
                }
                if (s[s.Length - 1] != obj.OriginalNode.Name)
                {
                    return(false);
                }
                return(kn5.GetObjectPath(obj.OriginalNode) == objectPath);
            }

            return(Flatten(root, x => {
                if (!(x is IKn5RenderableObject k))
                {
                    return true;
                }
                if (!TestObjectPath(k))
                {
                    return false;
                }
                if (textureName == null)
                {
                    return true;
                }
                var material = kn5.GetMaterial(k.OriginalNode.MaterialId);
                return material != null && material.TextureMappings.Where(y => y.Name != "txDetail" && y.Name != "txNormalDetail")
                .Any(m => m.Texture == textureName);
            }));
Ejemplo n.º 27
0
        private PaintShopFontSource([NotNull] string familyName, [CanBeNull] string filename, [CanBeNull] byte[] data)
        {
            FamilyName      = familyName;
            _filenameLazier = Lazier.Create(() => {
                if (filename != null)
                {
                    return(filename);
                }
                if (data == null)
                {
                    return(null);
                }

                string f;
                using (var sha1 = SHA1.Create()) {
                    f = Path.Combine(Path.GetTempPath(), "font-" + sha1.ComputeHash(data).ToHexString().ToLowerInvariant() + ".ttf");
                }
                if (!File.Exists(f))
                {
                    File.WriteAllBytes(f, data);
                }
                return(f);
            });
        }
 private void InitializeAccumulationDof()
 {
     _lazyAccumulationDofPoissonDiskSamples   = Lazier.Create(() => Reorder(UniformPoissonDiskSampler.SampleCircle(_accumulationDofIterations)));
     _lazyAccumulationDofPoissonSquareSamples = Lazier.Create(() => UniformPoissonDiskSampler.SampleSquare(_accumulationDofIterations, false).ToArray());
 }
Ejemplo n.º 29
0
 public PythonAppObject(IFileAcManager manager, string id, bool enabled) : base(manager, id, enabled)
 {
     AppIcon = Lazier.CreateAsync(TryToFindAppIconAsync);
     Windows = Lazier.CreateAsync(() => Task.Run(() => GetWindows().ToIReadOnlyListIfItIsNot()));
 }
Ejemplo n.º 30
0
 public WeatherObject(IFileAcManager manager, string id, bool enabled)
     : base(manager, id, enabled)
 {
     _temperatureDiapasonLazier = Lazier.Create(() => TemperatureDiapason == null ? null : Diapason.CreateDouble(TemperatureDiapason));
     _timeDiapasonLazier        = Lazier.Create(() => TimeDiapason == null ? null : Diapason.CreateTime(TimeDiapason));
 }