public TrackObject(IFileAcManager manager, string id, bool enabled) : base(manager, id, enabled) { InitializeLocationsOnce(); try { var information = GetLayouts(); if (information != null) { _layoutLocation = information.MainLayout; InitializeLocationsInner(_layoutLocation); LayoutId = information.SimpleMainLayout ? null : Path.GetFileName(_layoutLocation); IdWithLayout = information.SimpleMainLayout ? Id : $@"{Id}/{LayoutId}"; MultiLayouts = new BetterObservableCollection<TrackObjectBase>( information.AdditionalLayouts.Select(x => { var c = new TrackExtraLayoutObject(manager, this, enabled, x); c.PropertyChanged += Configuration_PropertyChanged; return c; }).Prepend((TrackObjectBase)this)); return; } } catch (AcErrorException e) { AddError(e.AcError); } InitializeLocationsInner(Path.Combine(Location, "ui")); _layoutLocation = null; LayoutId = null; IdWithLayout = Id; MultiLayouts = null; }
public void Test() { var array = new BetterObservableCollection<string> { "Cat", "Dog", "Rat" }; var wrapped = WrappedCollection.Create(array, s => "Big " + s); var second = WrappedCollection.Create(wrapped, s => s.Replace("Big", "Small")); array.Add("Mouse"); Debug.WriteLine(string.Join(", ", array)); Debug.WriteLine(string.Join(", ", wrapped)); Debug.WriteLine(string.Join(", ", second)); Assert.AreEqual("Big Cat", wrapped[0]); Assert.AreEqual("Big Rat", wrapped[2]); Assert.AreEqual("Small Cat", second[0]); Assert.AreEqual("Small Rat", second[2]); Assert.AreEqual(4, wrapped.Count); array.Add("Moose"); Debug.WriteLine(string.Join(", ", array)); Debug.WriteLine(string.Join(", ", wrapped)); Debug.WriteLine(string.Join(", ", second)); Assert.AreEqual("Big Moose", wrapped[4]); Assert.AreEqual("Small Moose", second[4]); array.Insert(1, "Mole"); Debug.WriteLine(string.Join(", ", array)); Debug.WriteLine(string.Join(", ", wrapped)); Debug.WriteLine(string.Join(", ", second)); Assert.AreEqual("Big Mole", wrapped[1]); Assert.AreEqual("Big Dog", wrapped[2]); Assert.AreEqual("Small Mole", second[1]); Assert.AreEqual("Small Dog", second[2]); array.Remove("Mouse"); Assert.AreEqual(5, wrapped.Count); Assert.AreEqual(5, second.Count); array.ReplaceEverythingBy(new[] { "Human", "Alien" }); Assert.AreEqual("Big Human", wrapped[0]); Assert.AreEqual("Big Alien", wrapped[1]); Assert.AreEqual("Small Human", second[0]); Assert.AreEqual("Small Alien", second[1]); }
public ViewModel(IReadOnlyDictionary<string, WidgetEntry> widgets) { Widgets = widgets; var active = SettingsHolder.Drive.QuickSwitchesList; // clean up all invalid entries from saved list if (active.Any(x => !widgets.Keys.Contains(x))) { active = active.Where(widgets.Keys.Contains).ToArray(); SettingsHolder.Drive.QuickSwitchesList = active; } Stored = new BetterObservableCollection<WidgetEntry>(Widgets.Values.Where(x => !active.Contains(x.Key))); Added = new BetterObservableCollection<WidgetEntry>(active.Select(x => Widgets.GetValueOrDefault(x)).NonNull()); Added.CollectionChanged += Added_CollectionChanged; }
public BrandBadgeEditor(CarObject car) { Car = car; InitializeComponent(); DataContext = this; Buttons = new[] { OkButton, CreateExtraDialogButton(AppStrings.Common_SelectFile, SelectFile), CreateExtraDialogButton(AppStrings.Common_ViewUserFolder, () => FilesStorage.Instance.OpenContentDirectoryInExplorer(ContentCategory.BrandBadges)), CancelButton }; Closing += BrandBadgeEditor_Closing; FilesStorage.Instance.Watcher(ContentCategory.BrandBadges).Update += BrandBadgeEditor_Update; Icons = new BetterObservableCollection<FilesStorage.ContentEntry>(FilesStorage.Instance.GetContentDirectory(ContentCategory.BrandBadges)); UpdateSelected(); }
public ViewModel() { FilesStorage.Instance.Watcher(ContentCategory.CarCategories).Update += SelectTrackDialog_CategoriesViewModel_LibraryUpdate; Categories = new BetterObservableCollection<SelectCategory>(ReloadCategories()); }
public BatchAction_AddTag() : base("Add tag", "Modify list of tags for several cars easily", "UI", "Batch.AddTag") { DisplayApply = "Apply"; Tags = new BetterObservableCollection <string>(); }
public ViewModel() { Entries = new BetterObservableCollection <TagEntry>(GetList()); }
/// <summary> /// Start server (all stdout stuff will end up in RunningLog). /// </summary> /// <exception cref="InformativeException">For some predictable errors.</exception> /// <exception cref="Exception">Process starting might cause loads of problems.</exception> public async Task RunServer(IProgress <AsyncProgressEntry> progress = null, CancellationToken cancellation = default(CancellationToken)) { StopServer(); if (!Enabled) { throw new InformativeException("Can’t run server", "Preset is disabled."); } if (HasErrors) { throw new InformativeException("Can’t run server", "Preset has errors."); } if (TrackId == null) { throw new InformativeException("Can’t run server", "Track is not specified."); } var serverExecutable = GetServerExecutableFilename(); if (!File.Exists(serverExecutable)) { throw new InformativeException("Can’t run server", "Server’s executable not found."); } if (SettingsHolder.Online.ServerPresetsAutoSave) { SaveCommand.Execute(); } if (SettingsHolder.Online.ServerPresetsUpdateDataAutomatically) { await PrepareServer(progress, cancellation); } var welcomeMessageLocal = IniObject?["SERVER"].GetNonEmpty("WELCOME_MESSAGE"); var welcomeMessageFilename = WelcomeMessagePath; if (welcomeMessageLocal != null && welcomeMessageFilename != null && File.Exists(welcomeMessageFilename)) { using (FromServersDirectory()) { var local = new FileInfo(welcomeMessageLocal); if (!local.Exists || new FileInfo(welcomeMessageFilename).LastWriteTime > local.LastWriteTime) { try { File.Copy(welcomeMessageFilename, welcomeMessageLocal, true); } catch (Exception e) { Logging.Warning(e); } } } } var log = new BetterObservableCollection <string>(); RunningLog = log; // await if (WrapperUsed) { await RunWrapper(serverExecutable, log, progress, cancellation); } else { await RunAcServer(serverExecutable, log, progress, cancellation); } }
public ViewModel(List <MostUsedCar> cars, List <MostUsedTrack> tracks) { CarEntries = new BetterObservableCollection <MostUsedCar>(cars); TrackEntries = new BetterObservableCollection <MostUsedTrack>(tracks); }
public UploadLogger([NotNull] BetterObservableCollection <string> destination) { _destination = destination; _destination.Clear(); }
public ExampleCarsViewModel(List <CarWithTyres> cars) { CommonTyresList = new BetterObservableCollection <CommonTyres>(); CarsList = cars; UpdateListFilterLater(); UpdateSummary(); CarsView = new BetterListCollectionView(CarsList) { Filter = o => _listFilterInstance?.Test(((CarWithTyres)o).Car) ?? true }; TestKeys = new BetterObservableCollection <SettingEntry>(); TestKeysView = new BetterListCollectionView(TestKeys) { GroupDescriptions = { new PropertyGroupDescription(nameof(SettingEntry.Tag)) }, CustomSort = KeyComparer.Instance }; (_saveable = new SaveHelper <Data>("CreateTyres.ExampleCars", () => new Data { Checked = CarsList.ToDictionary(x => x.Car.Id, x => Tuple.Create(x.IsChecked, x.Tyres.Where(y => y.IsChecked).Select(y => y.Entry.DisplayName).ToArray())), Filter = CarsFilter, TyresName = TyresName, TyresShortName = TyresShortName, }, o => { for (var i = CarsList.Count - 1; i >= 0; i--) { var c = CarsList[i]; var e = o.Checked?.GetValueOrDefault(c.Car.Id); c.IsChecked = o.Checked == null ? c.Car.Author == AcCommonObject.AuthorKunos : e?.Item1 == true; for (var j = c.Tyres.Count - 1; j >= 0; j--) { var tyre = c.Tyres[j]; tyre.IsChecked = e?.Item2.ArrayContains(tyre.Entry.DisplayName) == true; } } CarsFilter = o.Filter; TyresName = o.TyresName; TyresShortName = o.TyresShortName; })).Initialize(); UpdateListFilter(); CarsList.ForEach(x => { x.PropertyChanged += (sender, args) => { if (args.PropertyName == nameof(CarWithTyres.IsChecked)) { UpdateSummary(); } }; x.Tyres.ForEach(y => { y.PropertyChanged += (sender, args) => { if (args.PropertyName == nameof(CarTyres.IsChecked)) { UpdateSummary(); } }; }); }); }
private async Task UpdateInner(UpdateMode mode, bool background = false) { var errorMessage = ""; try { if (!background) { CurrentDrivers.Clear(); OnPropertyChanged(nameof(CurrentDrivers)); Status = ServerStatus.Loading; IsAvailable = false; } SetMissingTrackErrorIfNeeded(ref errorMessage); SetMissingCarErrorIfNeeded(ref errorMessage); if (!string.IsNullOrWhiteSpace(errorMessage)) return; if (!IsLan && SteamIdHelper.Instance.Value == null) { throw new InformativeException(ToolsStrings.Common_SteamIdIsMissing); } if (mode == UpdateMode.Full) { var newInformation = await Task.Run(() => IsLan || SettingsHolder.Online.LoadServerInformationDirectly ? KunosApiProvider.TryToGetInformationDirect(Ip, PortC) : KunosApiProvider.TryToGetInformation(Ip, Port)); if (newInformation == null) { errorMessage = ToolsStrings.Online_Server_CannotRefresh; return; } else if (!UpdateValuesFrom(newInformation)) { errorMessage = ToolsStrings.Online_Server_NotImplemented; return; } } var pair = SettingsHolder.Online.ThreadsPing ? await Task.Run(() => KunosApiProvider.TryToPingServer(Ip, Port, SettingsHolder.Online.PingTimeout)) : await KunosApiProvider.TryToPingServerAsync(Ip, Port, SettingsHolder.Online.PingTimeout); if (pair != null) { Ping = (long)pair.Item2.TotalMilliseconds; } else { Ping = null; errorMessage = ToolsStrings.Online_Server_CannotPing; return; } var information = await KunosApiProvider.TryToGetCurrentInformationAsync(Ip, PortC); if (information == null) { errorMessage = ToolsStrings.Online_Server_Unavailable; return; } ActualInformation = information; if (CurrentDrivers.ReplaceIfDifferBy(from x in information.Cars where x.IsConnected select new CurrentDriver { Name = x.DriverName, Team = x.DriverTeam, CarId = x.CarId, CarSkinId = x.CarSkinId })) { OnPropertyChanged(nameof(CurrentDrivers)); } // CurrentDriversCount = information.Cars.Count(x => x.IsConnected); List<CarObject> carObjects; if (CarsOrTheirIds.Select(x => x.CarObjectWrapper).Any(x => x?.IsLoaded == false)) { await Task.Delay(50); carObjects = new List<CarObject>(CarsOrTheirIds.Count); foreach (var carOrOnlyCarIdEntry in CarsOrTheirIds.Select(x => x.CarObjectWrapper).Where(x => x != null)) { var loaded = await carOrOnlyCarIdEntry.LoadedAsync(); carObjects.Add((CarObject)loaded); } } else { carObjects = (from x in CarsOrTheirIds where x.CarObjectWrapper != null select (CarObject)x.CarObjectWrapper.Value).ToList(); } foreach (var carObject in carObjects.Where(carObject => carObjects.Any(x => !x.SkinsManager.IsLoaded))) { await Task.Delay(50); await carObject.SkinsManager.EnsureLoadedAsync(); } List<CarEntry> cars; if (BookingMode) { cars = CarsOrTheirIds.Select(x => x.CarObject == null ? null : new CarEntry(x.CarObject) { AvailableSkin = x.CarObject.SelectedSkin }).ToList(); } else { cars = information.Cars.Where(x => x.IsEntryList) .GroupBy(x => x.CarId) .Select(g => { var group = g.ToList(); var id = group[0].CarId; var existing = Cars?.GetByIdOrDefault(id); if (existing != null) { var car = existing.CarObject; var availableSkinId = group.FirstOrDefault(y => y.IsConnected == false)?.CarSkinId; existing.Total = group.Count; existing.Available = group.Count(y => !y.IsConnected && y.IsEntryList); existing.AvailableSkin = availableSkinId == null ? null : availableSkinId == string.Empty ? car.GetFirstSkinOrNull() : car.GetSkinById(availableSkinId); return existing; } else { var car = carObjects.GetByIdOrDefault(id, StringComparison.OrdinalIgnoreCase); if (car == null) return null; var availableSkinId = group.FirstOrDefault(y => y.IsConnected == false)?.CarSkinId; return new CarEntry(car) { Total = group.Count, Available = group.Count(y => !y.IsConnected && y.IsEntryList), AvailableSkin = availableSkinId == null ? null : availableSkinId == string.Empty ? car.GetFirstSkinOrNull() : car.GetSkinById(availableSkinId) }; } }).ToList(); } if (cars.Contains(null)) { errorMessage = ToolsStrings.Online_Server_CarsDoNotMatch; return; } var changed = true; if (Cars == null || CarsView == null) { Cars = new BetterObservableCollection<CarEntry>(cars); CarsView = new ListCollectionView(Cars) { CustomSort = this }; CarsView.CurrentChanged += SelectedCarChanged; } else { // temporary removing listener to avoid losing selected car CarsView.CurrentChanged -= SelectedCarChanged; if (Cars.ReplaceIfDifferBy(cars)) { OnPropertyChanged(nameof(Cars)); } else { changed = false; } CarsView.CurrentChanged += SelectedCarChanged; } if (changed) { LoadSelectedCar(); } } catch (InformativeException e) { errorMessage = $"{e.Message}."; } catch (Exception e) { errorMessage = string.Format(ToolsStrings.Online_Server_UnhandledError, e.Message); Logging.Warning("UpdateInner(): " + e); } finally { ErrorMessage = errorMessage; if (!string.IsNullOrWhiteSpace(errorMessage)) { Status = ServerStatus.Error; } else if (Status == ServerStatus.Loading) { Status = ServerStatus.Ready; } AvailableUpdate(); } }
protected virtual ICollectionView GetCollectionView(BetterObservableCollection <TItem> items) { return((ListCollectionView)CollectionViewSource.GetDefaultView(items)); }
public ViewModel(bool changeAcRoot, bool changeSteamId) { ChangeAcRoot = changeAcRoot; ChangeSteamId = changeSteamId; FirstRun = ValuesStorage.GetBool(KeyFirstRun) == false; if (FirstRun) { ValuesStorage.Set(KeyFirstRun, true); } ReviewMode = !FirstRun && IsReviewNeeded(); Value = AcRootDirectory.Instance.IsReady ? AcRootDirectory.Instance.Value : AcRootDirectory.TryToFind(); #if DEBUG Value = Value?.Replace("D:", "C:"); #endif var steamId = SteamIdHelper.Instance.Value; SteamProfiles = new BetterObservableCollection<SteamProfile>(SteamIdHelper.TryToFind().Append(SteamProfile.None)); SteamProfile = SteamProfiles.GetByIdOrDefault(steamId) ?? SteamProfiles.First(); if (steamId != null && SteamProfile.SteamId != steamId) { SetSteamId(steamId); } }
private ContentInstallationManager() { Queue = new BetterObservableCollection <ContentInstallationEntry>(); }
public LapTimesManager() { Entries = new BetterObservableCollection<LapTimeEntry>(); }
public PluginsManager(string dir) { PluginsDirectory = dir; List = new BetterObservableCollection<PluginEntry>(); ReloadLocalList(); // TODO: Directory watching }
internal ViewModel() { Locales = new BetterObservableCollection <LocaleEntry>(LoadLocal().Distinct(new LocaleComparer())); LoadCurrentLocale(); LoadOtherLocales(); }