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); }
public ImageInformation(ImageViewerImageCallback imageCallback, ImageViewerDetailsCallback detailsCallback, int position) { _imageCallback = imageCallback; _detailsCallback = detailsCallback; _position = position; _details = Lazier.Create(GetDetails); }
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); }); }
public Emoji([NotNull] string id, [NotNull] IEmojiLoader loader, [NotNull] IEmojiInformationProvider informationProvider) { _id = id; _loader = loader; Image = Lazier.Create(LoadImageSource); Information = informationProvider.GetInformation(_id); }
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)); }
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)); }); }
private void UnloadDriverModel() { Remove(_driver); DisposeHelper.Dispose(ref _driver); _driverSteerAnimator = null; ObjectsChanged?.Invoke(this, EventArgs.Empty); }
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; }
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); }
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; } }
public SavedPresetEntry(string baseDirectory, string extension, string filename) { _baseDirectory = baseDirectory; _displayBaseDirectory = baseDirectory; _extension = extension; VirtualFilename = filename; _displayName = Lazier.Create(GetDisplayName); _shortDisplayName = Lazier.Create(GetShortDisplayName); }
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); })); }
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(); } }
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(); } }
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); }
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(); }
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); }
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>()); }
/// <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); }
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); }
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); }
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); } }
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()); }
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(); }
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); }
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); }));
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()); }
public PythonAppObject(IFileAcManager manager, string id, bool enabled) : base(manager, id, enabled) { AppIcon = Lazier.CreateAsync(TryToFindAppIconAsync); Windows = Lazier.CreateAsync(() => Task.Run(() => GetWindows().ToIReadOnlyListIfItIsNot())); }
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)); }