private async Task <bool> LoadAndPrepare() { #if !FORCE_UPDATE || !DEBUG if (!MainExecutingFile.IsPacked) { NonfatalError.Notify(ToolsStrings.AppUpdater_CannotUpdateApp, ToolsStrings.AppUpdater_UnpackedVersionMessage); LatestError = ToolsStrings.AppUpdater_UnpackedVersionMessage; return(false); } #endif if (_isPreparing) { return(false); } _isPreparing = true; UpdateIsReady = null; try { var data = await CmApiProvider.GetDataAsync($"app/get/{Branch}"); if (data == null) { throw new InformativeException(ToolsStrings.AppUpdater_CannotLoad, ToolsStrings.Common_MakeSureInternetWorks); } string preparedVersion = null; await Task.Run(() => { if (File.Exists(UpdateLocation)) { File.Delete(UpdateLocation); } using (var stream = new MemoryStream(data, false)) using (var archive = new ZipArchive(stream)) { preparedVersion = VersionFromData(archive.GetEntry(@"Manifest.json").Open().ReadAsStringAndDispose()); archive.GetEntry(@"Content Manager.exe").ExtractToFile(UpdateLocation); Logging.Write($"New version {preparedVersion} was extracted to “{UpdateLocation}”"); } }); UpdateIsReady = preparedVersion; return(true); } catch (UnauthorizedAccessException) { NonfatalError.Notify(ToolsStrings.AppUpdater_AccessIsDenied, ToolsStrings.AppUpdater_AccessIsDenied_Commentary); LatestError = ToolsStrings.AppUpdater_AccessIsDenied_Short; } catch (Exception e) { NonfatalError.Notify(ToolsStrings.AppUpdater_CannotLoad, ToolsStrings.AppUpdater_CannotLoad_Commentary, e); LatestError = ToolsStrings.AppUpdater_CannotLoadShort; } finally { _isPreparing = false; } return(false); }
public static void RenameList(string key, string newName) { try { File.Move(Path.Combine(Instance.RootDirectory, key + Extension), Path.Combine(Instance.RootDirectory, newName + Extension)); Instance.Rescan(); } catch (Exception e) { NonfatalError.Notify("Can’t rename list", e); } }
public static bool TryToInstallModule() { try { return(InstallModule()); } catch (Exception e) { NonfatalError.Notify("Can’t install UI module", e); return(false); } }
private static async Task ShotAndApply(string filename, bool isEnabled, Func <Task> run) { if (Keyboard.Modifiers.HasFlag(ModifierKeys.Alt)) { await ApplyExisting(filename); return; } if (!isEnabled) { return; } if (!ValuesStorage.GetBool(KeyUpdatePreviewMessageShown) && ModernDialog.ShowMessage( ImportantTips.Entries.GetByIdOrDefault(@"trackPreviews")?.Content, AppStrings.Common_HowTo_Title, MessageBoxButton.OK) != MessageBoxResult.OK) { return; } var directory = FileUtils.GetDocumentsScreensDirectory(); var shots = FileUtils.GetFilesSafe(directory); await run(); if (ScreenshotsConverter.CurrentConversion?.IsCompleted == false) { await ScreenshotsConverter.CurrentConversion; } var newShots = FileUtils.GetFilesSafe(directory) .Where(x => !shots.Contains(x) && Regex.IsMatch(x, @"\.(jpe?g|png|bmp)$", RegexOptions.IgnoreCase)).ToList(); if (!newShots.Any()) { NonfatalError.Notify(ControlsStrings.AcObject_CannotUpdatePreview, ControlsStrings.AcObject_CannotUpdatePreview_TrackCommentary); return; } ValuesStorage.Set(KeyUpdatePreviewMessageShown, true); var shot = new ImageViewer(newShots) { Model = { MaxImageHeight = CommonAcConsts.TrackPreviewHeight, MaxImageWidth = CommonAcConsts.TrackPreviewWidth } }.ShowDialogInSelectFileMode(); if (shot == null) { return; } ApplyExistring(shot, filename); }
private void OnEndpointsChanged(object sender, EventArgs eventArgs) { try { _audioDevicesList = GetAudioDevicesList(); Model.AudioOutputDevices = _audioDevicesList; } catch (Exception e) { NonfatalError.NotifyBackground("Can’t get the list of audio devices", e); } }
private void OnEndpointsChanged(object sender, EventArgs eventArgs) { try { _audioDevicesList = GetAudioDevicesList(); Model.AudioOutputDevices = _audioDevicesList; } catch (Exception e) { NonfatalError.NotifyBackground(AppStrings.AcSettings_Audio_CantGetTheListOfAudioDevices, e); } }
public UIElement Initialize() { try { _vlcPlayer.Initialize(PluginsManager.Instance.GetPluginDirectory("VLC"), @"--ignore-config", @"--no-video-title", @"--no-sub-autodetect-file"); } catch (Exception ex) { NonfatalError.NotifyBackground(ControlsStrings.VideoViewer_CannotPlay, ControlsStrings.VideoViewer_CannotPlay_Commentary, ex); } return(_vlcPlayer); }
public App() { // FirstFloor.ModernUI initialization (library used here is a forked version from Content Manager project with extra bits) ValuesStorage.Initialize(TypoModel.DataFilename, "_key_zsu4b3ws1k17ties_" + Environment.UserName, true); CacheStorage.Initialize(); Logging.Initialize(TypoModel.LogFilename, false); Logging.Write($"App version: {BuildInformation.AppVersion} ({BuildInformation.Platform}, {WindowsVersionHelper.GetVersion()})"); if (Directory.GetFiles(TypoModel.DataDirectory).Length == 0) { using (var memory = new MemoryStream(Typo4.Properties.Resources.Typo4Data)) { new ZipArchive(memory).ExtractToDirectory(TypoModel.DataDirectory); } } AppearanceManager.Current.Initialize(); AppearanceManager.Current.SetTheme(new Uri("pack://application:,,,/Typo4;component/Assets/AppTheme.xaml", UriKind.Absolute)); AppearanceManager.Current.BoldTitleLinks = false; AppearanceManager.Current.LargerTitleLinks = false; AppearanceManager.Current.SubMenuFontSize = FontSize.Small; Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("pack://application:,,,/Typo4;component/Assets/AppAssets.xaml", UriKind.Absolute) }); MuiSystemAccent.Initialize(); NonfatalError.Initialize(); AppIconService.Initialize(this); FatalErrorMessage.Register(this); // All logic in relationship to UI _typoModel = new TypoModel(); // Some more UI initialization bits PrepareUi(); AppShortcut.Initialize("x4fab.Typo4", "Typo4"); Toast.SetDefaultAction(() => (Current.Windows.OfType <ModernWindow>().FirstOrDefault(x => x.IsActive) ?? Current.MainWindow as ModernWindow)?.BringToFront()); BbCodeBlock.OptionEmojiProvider = this; // Let’s at least try to handle stuff properly AppDomain.CurrentDomain.ProcessExit += OnProcessExit; // Log stuff using FirstFloor.ModernUI library TypoLogging.Logger = (s, m, p, l) => Logging.Write($"{s} (Typo)", m, p, l); TypoLogging.TypoLoggingNonFatalErrorHandler = (s, c, e) => NonfatalError.Notify(s, c, e); // Most of the time app should work from system tray _typoModel.Initialize(); _trayInterface = new TrayInterface(_typoModel); // Close only manually ShutdownMode = ShutdownMode.OnExplicitShutdown; // Fancy blur for all windows DpiAwareWindow.NewWindowCreated += OnWindowLoaded; }
public static async Task FixLightingAsync(ShowroomObject showroom) { try { using (WaitingDialog.Create("Updating model…")) { await Task.Run(() => FixLighting(showroom)); } } catch (Exception e) { NonfatalError.Notify("Can’t update model", e); } }
private bool SaveEdited() { try { File.WriteAllText(Location, Content); return(true); } catch (Exception e) { NonfatalError.Notify(ToolsStrings.PpFilterObject_CannotSave, ToolsStrings.PpFilterObject_MakeSureCouldBeOverwritten, e); return(false); } }
public void Start(int port, [CanBeNull] string filename) { #if DEBUG var log = this; #else var log = new NullLog(); #endif _server = new WebServer($"http://+:{port}/", log, RoutingStrategy.Wildcard); // HTTP part: index webpage, static files nearby (if any) var pages = new PagesProvider(filename); _server.RegisterModule(new WebApiModule()); _server.Module <WebApiModule>().RegisterController(() => new IndexPageController(pages)); if (Directory.Exists(pages.StaticDirectory)) { _server.RegisterModule(new StaticFilesModule(new Dictionary <string, string> { [@"/"] = pages.StaticDirectory }) { UseRamCache = false, UseGzip = false }); } // Websockets part var module = new WebSocketsModule(); _server.RegisterModule(module); _sharedServer = new PublishDataSocketsServer(@"Current Race Shared Memory Server"); module.RegisterWebSocketsServer(@"/api/ws/shared", _sharedServer); _statsServer = new PublishDataSocketsServer(@"Current Race Stats Server"); module.RegisterWebSocketsServer(@"/api/ws/stats", _statsServer); // Starting try { _server.RunAsync(); } catch (HttpListenerException e) { NonfatalError.NotifyBackground("Can’t start web server", $"Don’t forget to allow port’s usage with something like “netsh http add urlacl url=\"http://+:{port}/\" user=everyone”.", e, new[] { new NonfatalErrorSolution($"Use “netsh” to allow usage of port {port}", null, token => { Process.Start(new ProcessStartInfo { FileName = "cmd", Arguments = $"/C netsh http add urlacl url=\"http://+:{port}/\" user=everyone & pause", Verb = "runas" }); return(Task.Delay(1000, token)); }) }); } catch (Exception e) { Logging.Error(e); } }
public void OnProgress(Game.ProgressState progress) { switch (progress) { case Game.ProgressState.Preparing: Model.WaitingStatus = AppStrings.Race_Preparing; break; case Game.ProgressState.Launching: if (AcRootDirectory.CheckDirectory(MainExecutingFile.Directory) && MainExecutingFile.Name != "AssettoCorsa.exe" && new IniFile(AcPaths.GetCfgVideoFilename())["CAMERA"].GetNonEmpty("MODE") == "OCULUS" && MessageDialog.Show( "Oculus Rift might not work properly with Content Manager is in AC root folder. It’s better to move it to avoid potential issues.", "Important note", new MessageDialogButton { [MessageBoxResult.Yes] = "Move it now", [MessageBoxResult.No] = "Ignore" }, "oculusRiftWarningMessage") == MessageBoxResult.Yes) { try { var newLocation = FilesStorage.Instance.GetFilename(MainExecutingFile.Name); File.Copy(MainExecutingFile.Location, newLocation, true); WindowsHelper.ViewFile(newLocation); ProcessExtension.Start(newLocation, new[] { @"--restart", @"--move-app=" + MainExecutingFile.Location }); Environment.Exit(0); } catch (Exception e) { NonfatalError.Notify("Failed to move Content Manager executable", "I’m afraid you’ll have to do it manually.", e); } } if (SettingsHolder.Drive.SelectedStarterType == SettingsHolder.DriveSettings.DeveloperStarterType) { Model.WaitingStatus = "Now, run AC…"; } else { Model.WaitingStatus = _mode == GameMode.Race ? AppStrings.Race_LaunchingGame : _mode == GameMode.Replay ? AppStrings.Race_LaunchingReplay : AppStrings.Race_LaunchingBenchmark; } break; case Game.ProgressState.Waiting: Model.WaitingStatus = _mode == GameMode.Race ? AppStrings.Race_Waiting : _mode == GameMode.Replay ? AppStrings.Race_WaitingReplay : AppStrings.Race_WaitingBenchmark; break; case Game.ProgressState.Finishing: RevertSizeFix().Ignore(); Model.WaitingStatus = AppStrings.Race_CleaningUp; break; default: throw new ArgumentOutOfRangeException(nameof(progress), progress, null); } }
public async Task <List <string> > UsingsRescan(IProgress <AsyncProgressEntry> progress = null, CancellationToken cancellation = default(CancellationToken)) { try { await EnsureLoadedAsync(); if (cancellation.IsCancellationRequested) { return(null); } await CarsManager.Instance.EnsureLoadedAsync(); if (cancellation.IsCancellationRequested) { return(null); } var i = 0; var cars = CarsManager.Instance.LoadedOnly.ToList(); var list = (await cars.Select(async car => { if (cancellation.IsCancellationRequested) { return(null); } progress?.Report(car.DisplayName, i++, cars.Count); return(new { CarId = car.Id, DriverModelId = (await Task.Run(() => new IniFile(car.Location, @"driver3d.ini"), cancellation)) ["MODEL"].GetNonEmpty("NAME") }); }).WhenAll(12, cancellation)).Where(x => x != null && x.DriverModelId != null).ToListIfItIsNot(); if (cancellation.IsCancellationRequested) { return(null); } foreach (var fontObject in LoadedOnly) { fontObject.UsingsCarsIds = list.Where(x => x.DriverModelId == fontObject.AcId).Select(x => x.CarId).ToArray(); } return(list.Select(x => x.DriverModelId).Distinct().Where(id => GetWrapperById(id + DriverModelObject.FileExtension) == null).ToList()); } catch (Exception e) when(e.IsCanceled()) { return(null); } catch (Exception e) { NonfatalError.Notify(ToolsStrings.Fonts_RescanUsings, e); return(null); } finally { LastUsingsRescan = DateTime.Now; } }
private async void UpdatePreview() { await Task.Run(() => { const string sphereId = "__sphere"; var sphereDirectory = CarsManager.Instance.Directories.GetLocation(sphereId, true); try { using (CarsManager.Instance.IgnoreChanges()) { if (!Directory.Exists(sphereDirectory)) { Directory.CreateDirectory(sphereDirectory); using (var stream = new MemoryStream(BinaryResources.ShowroomPreviewSphere)) using (var archive = new ZipArchive(stream)) { archive.ExtractToDirectory(sphereDirectory); } } var resultDirectory = Showroom.Shot(new Showroom.ShotProperties { AcRoot = AcRootDirectory.Instance.Value, CarId = sphereId, ShowroomId = SelectedObject.Id, SkinIds = new[] { @"0" }, Filter = @"default", Mode = Showroom.ShotMode.Fixed, UseBmp = true, DisableWatermark = true, DisableSweetFx = true, MaximizeVideoSettings = true, SpecialResolution = false, Fxaa = true, FixedCameraPosition = @"-1.8,0.8,3", FixedCameraLookAt = @"0,0.5,0", FixedCameraFov = 40, TemporaryDirectory = SettingsHolder.Content.TemporaryFilesLocationValue, }); if (resultDirectory == null) { throw new Exception(AppStrings.Common_ShootingCancelled); } ImageUtils.ApplyPreview(Path.Combine(resultDirectory, "0.bmp"), SelectedObject.PreviewImage, true, null); } } catch (Exception e) { NonfatalError.Notify(AppStrings.Showroom_CannotUpdatePreview, e); } finally { if (Directory.Exists(sphereDirectory)) { Directory.Delete(sphereDirectory, true); } } }); }
private async Task CheckRegistriesAsync() { foreach (var registry in SettingsHolder.Content.CupRegistries.Split(new[] { ';', '\n', ' ' }, StringSplitOptions.RemoveEmptyEntries)) { try { await LoadList(registry); } catch (Exception e) { NonfatalError.NotifyBackground("Can’t check registry for content updates", e); } } }
public void EnsureResolutionIsCorrect() { try { if (Ini == null || IsReloading) { Reload(); } } catch (Exception e) { NonfatalError.NotifyBackground("Can’t ensure used resolution is valid", e); } }
protected override async Task <bool> LoadOverride(IProgress <AsyncProgressEntry> progress, CancellationToken cancellation) { if (_id != null) { var car = CarsManager.Instance.GetById(_id); if (car != null) { progress.Report(AsyncProgressEntry.Indetermitate); ObsoleteCars = new List <ObsoleteDetails> { await Task.Run(() => GetDetails(car, _models, true)) }; } else { ObsoleteCars = new List <ObsoleteDetails>(); } } else { var entries = new List <ObsoleteDetails>(); var filter = _filter == null ? null : Filter.Create(CarObjectTester.Instance, _filter); progress.Report(AsyncProgressEntry.FromStringIndetermitate("Loading cars…")); await CarsManager.Instance.EnsureLoadedAsync(); IEnumerable <CarObject> carsEnumerable = CarsManager.Instance.LoadedOnly.OrderBy(x => x.Name); if (filter != null) { carsEnumerable = carsEnumerable.Where(filter.Test); } var cars = carsEnumerable.ToList(); for (var i = 0; i < cars.Count; i++) { var car = cars[i]; progress.Report(new AsyncProgressEntry(car.Name, i, cars.Count)); try { var details = await Task.Run(() => GetDetails(car, _models, false)); if (details != null) { entries.Add(details); } } catch (Exception e) { NonfatalError.Notify($"Can’t check {car.DisplayName}", e); } } ObsoleteCars = entries; } return(ObsoleteCars.Count > 0); }
private async Task CheckRegistriesAsync() { foreach (var registry in SettingsHolder.Content.CupRegistriesList) { try { await LoadList(registry); } catch (Exception e) { NonfatalError.NotifyBackground("Can’t check registry for content updates", e); } } }
public override async Task Drive(Game.BasicProperties basicProperties, Game.AssistsProperties assistsProperties, Game.ConditionProperties conditionProperties, Game.TrackProperties trackProperties) { var selectedCar = CarsManager.Instance.GetById(basicProperties.CarId ?? ""); var selectedTrack = TracksManager.Instance.GetLayoutById(basicProperties.TrackId ?? "", basicProperties.TrackConfigurationId); IEnumerable <Game.AiCar> botCars; try { using (var waiting = new WaitingDialog()) { if (selectedCar == null || !selectedCar.Enabled) { ModernDialog.ShowMessage(AppStrings.Drive_CannotStart_SelectNonDisabled, AppStrings.Drive_CannotStart_Title, MessageBoxButton.OK); return; } if (selectedTrack == null) { ModernDialog.ShowMessage(AppStrings.Drive_CannotStart_SelectTrack, AppStrings.Drive_CannotStart_Title, MessageBoxButton.OK); return; } botCars = await RaceGridViewModel.GenerateGameEntries(waiting.CancellationToken); if (waiting.CancellationToken.IsCancellationRequested) { return; } if (botCars == null || !botCars.Any()) { ModernDialog.ShowMessage(AppStrings.Drive_CannotStart_SetOpponent, AppStrings.Drive_CannotStart_Title, MessageBoxButton.OK); return; } } } catch (Exception e) when(e.IsCanceled()) { return; } catch (Exception e) { NonfatalError.Notify("Can’t create race grid", e); return; } basicProperties.Ballast = RaceGridViewModel.PlayerBallast; basicProperties.Restrictor = RaceGridViewModel.PlayerRestrictor; await StartAsync(new Game.StartProperties { BasicProperties = basicProperties, AssistsProperties = assistsProperties, ConditionProperties = conditionProperties, TrackProperties = trackProperties, ModeProperties = GetModeProperties(botCars) }); }
public async Task <IEnumerable <PluginEntry> > DownloadAndParseList() { try { var loaded = await CmApiProvider.GetStringAsync("plugins/list"); return(loaded == null ? null : JsonConvert.DeserializeObject <PluginEntry[]>(loaded).Where(x => x.IsAllRight)); } catch (Exception e) { NonfatalError.NotifyBackground("Can’t download plugins list", e); return(null); } }
public static void RenameAll() { try { foreach (var file in GetWithoutExtension()) { File.Move(file, file + ReplayObject.ReplayExtension); } } catch (Exception e) { NonfatalError.Notify(ToolsStrings.Replay_CannotRenameReplays, ToolsStrings.Replay_CannotRenameReplays_Commentary, e); } }
private static void ApplyExisting(string source, string previewImage) { try { var cropped = ImageEditor.Proceed(source, new Size(CommonAcConsts.TrackPreviewWidth, CommonAcConsts.TrackPreviewHeight)); using (var t = FileUtils.RecycleOriginal(previewImage)) { cropped?.SaveTo(t.Filename); } } catch (Exception e) { NonfatalError.Notify(ControlsStrings.AcObject_CannotUpdatePreview, e); } }
public static async Task CheckAsync() { if (Check()) { try { await FixAsync(); } catch (Exception e) { Logging.Warning(e); NonfatalError.Notify("Failed to fix the issue with FTH", e); } } }
public static void ViewInBrowser([CanBeNull] string url) { if (string.IsNullOrWhiteSpace(url)) { return; } try { Process.Start(url); } catch (Exception) { NonfatalError.Notify("Can’t open link", $"App tried to open: “{url}”"); } }
public void Dispose() { // do not dispose _sharedCancellationTokenSource cause it’s shared try { DisposeHelper.Dispose(ref _keyboard); } catch (Exception e) { NonfatalError.NotifyBackground("Can’t remove events hook", e); } AcSharedMemory.Instance.Start -= OnStart; }
private void OnCommentDelete(WorkshopComment comment) { _busyEdit.Task(async() => { try { await WorkshopHolder.Client.DeleteAsync($"{_url}/{comment.Id}"); Comments.Remove(comment); ++CommentsDeleted; } catch (Exception e) { NonfatalError.Notify("Failed to edit a comment", e); } }); }
/// <summary> /// Returns true if MainWindow should be shown afterwards. /// </summary> public static async Task <bool> ProcessArguments(IEnumerable <string> arguments, TimeSpan extraDelay = default(TimeSpan)) { var showMainWindow = false; var list = arguments.ToList(); if (_previousArguments?.SequenceEqual(list) == true) { return(false); } _previousArguments = list; var remote = (await list.Select(async x => Tuple.Create(x, ContentInstallationManager.IsRemoteSource(x) || ContentInstallationManager.IsAdditionalContent(x) ? x : await ContentInstallationManager.IsRemoteSourceFlexible(x)) ).WhenAll()).Where(x => x.Item2 != null).ToList(); if (remote.Any()) { list = list.ApartFrom(remote.Select(x => x.Item1)).ToList(); if ((await remote.Select(x => ContentInstallationManager.Instance.InstallAsync(x.Item2, new ContentInstallationParams { AllowExecutables = true })).WhenAll()).All(x => !x)) { await Task.Delay(ContentInstallationManager.OptionFailedDelay); } } foreach (var arg in list) { var result = await ProcessArgument(arg); if (extraDelay != TimeSpan.Zero) { await Task.Delay(extraDelay); } if (result == ArgumentHandleResult.FailedShow) { NonfatalError.Notify(AppStrings.Main_CannotProcessArgument, AppStrings.Main_CannotProcessArgument_Commentary); } if (result == ArgumentHandleResult.SuccessfulShow || result == ArgumentHandleResult.FailedShow) { showMainWindow = true; } } _previousArguments = null; return(showMainWindow); }
private static async Task <ChangeableObservableCollection <TyresMachineInfo> > LoadMachinesAsyncInner() { FilesStorage.Instance.Watcher(ContentCategory.NeuralTyresMachines).Update += OnUpdate; _list = new ChangeableObservableCollection <TyresMachineInfo>(await Task.Run(() => GetList())); return(_list); IEnumerable <TyresMachineInfo> GetList() { return(FilesStorage.Instance.GetContentFiles(ContentCategory.NeuralTyresMachines) .TryToSelect(CreateTyresMachineInfo, e => NonfatalError.NotifyBackground("Failed to load tyres machine", e)) .ToList()); } }
private void SaveDrivers() { try { var file = new IniFile(); foreach (var driver in SavedDrivers) { driver.Save(file); } file.Save(DriversFilename); } catch (Exception e) { NonfatalError.Notify("Can’t save drivers list", e); } }
private static void ManualInstallation([CanBeNull] Exception e, string directory) { var downloadUrl = @"https://drive.google.com/uc?id=1vPW58x0AsD3XzSSq8MzN9FEuZt6vGTLq"; NonfatalError.Notify("Can’t download the package", $"You can try to [url={BbCodeBlock.EncodeAttribute(downloadUrl)}]download[/url] and install it manually. Don’t forget to restart CM after it was installed.", e, new[] { new NonfatalErrorSolution("Open destination folder", null, t => { WindowsHelper.ViewDirectory(directory); return(Task.Delay(0)); }, "FolderIconData"), }); }