private async Task SelectDifferent(string presetFilename = null) { if (!SettingsHolder.CustomShowroom.CustomShowroomPreviews) { return; } using (var waiting = WaitingDialog.Create("Scanning…")) { var list = Entries.ToList(); var cancellation = waiting.CancellationToken; await Task.Run(() => { var checksum = CmPreviewsTools.GetChecksum(presetFilename); for (var i = 0; i < list.Count; i++) { if (cancellation.IsCancellationRequested) { return; } var entry = list[i]; waiting.Report(new AsyncProgressEntry(entry.Car.DisplayName, i, list.Count)); var selected = entry.Car.EnabledOnlySkins.Where(x => GetChecksum(x.PreviewImage) != checksum).ToList(); ActionExtension.InvokeInMainThread(() => entry.SelectedSkins = selected); } }); } }
public void JoinRequest(DiscordJoinRequest request, CancellationToken cancellation, Action <DiscordJoinRequestReply> callback) { ActionExtension.InvokeInMainThreadAsync(async() => { try { var dialog = new DiscordJoinRequestDialog(request); cancellation.Register(() => ActionExtension.InvokeInMainThreadAsync(() => { if (!dialog.IsLoaded) { dialog.Loaded += (s, e) => dialog.Close(); } else if (dialog.IsVisible) { try { dialog.Close(); } catch { // ignored } } })); switch (await dialog.ShowAndWaitAsync()) { case MessageBoxResult.Yes: callback(DiscordJoinRequestReply.Yes); break; case MessageBoxResult.No: callback(DiscordJoinRequestReply.No); break; } } catch (Exception e) { Logging.Warning(e); } }); }
public static ServerInformationComplete[] TryToGetList(IProgress <int> progress = null) { if (SteamIdHelper.Instance.Value == null) { throw new InformativeException(ToolsStrings.Common_SteamIdIsMissing); } for (var i = 0; i < ServersNumber && ServerUri != null; i++) { if (progress != null) { var j = i; ActionExtension.InvokeInMainThread(() => { progress.Report(j); }); } var uri = ServerUri; var requestUri = $@"http://{uri}/lobby.ashx/list?guid={SteamIdHelper.Instance.Value}"; try { var watch = Stopwatch.StartNew(); var parsed = LoadList(requestUri, OptionWebRequestTimeout, ServerInformationComplete.Deserialize); Logging.Write($"{watch.Elapsed.TotalMilliseconds:F1} ms"); return(parsed); } catch (Exception e) { Logging.Warning(e); } NextServer(); } return(null); }
public static void MarkForFutherRemoval(string skinDirectory) { ActionExtension.InvokeInMainThreadAsync(() => { _pauseCleanUp = DateTime.Now + TimeSpan.FromMinutes(2d); ValuesStorage.Storage.SetStringList(_key, ValuesStorage.Storage.GetStringList(_key).Union(new[] { skinDirectory })); }); }
private static bool OnPaste() { if (VisualExtension.IsInputFocused()) { return(false); } try { if (Clipboard.ContainsData(DataFormats.FileDrop)) { var data = Clipboard.GetFileDropList().OfType <string>().ToList(); ActionExtension.InvokeInMainThreadAsync(() => ProcessArguments(data, true)); return(true); } if (Clipboard.ContainsData(DataFormats.UnicodeText)) { var list = Clipboard.GetText().ToLines(); if (list.Length > 0 && list.All(x => !string.IsNullOrWhiteSpace(x))) { ActionExtension.InvokeInMainThreadAsync(() => ProcessArguments(list, true)); return(true); } } } catch (Exception e) { Logging.Warning(e); } return(false); }
private async Task UpdateList() { if (!_locallyLoaded) { ReloadLocalList(); } var list = await DownloadAndParseList(); if (list == null) { return; } ActionExtension.InvokeInMainThreadAsync(() => { foreach (var plugin in list) { if (plugin.IsObsolete || plugin.IsHidden && !SettingsHolder.Common.DeveloperMode) { continue; } var local = GetById(plugin.Id); if (local != null) { List.Remove(local); plugin.InstalledVersion = local.InstalledVersion; } List.Add(plugin); } ListUpdated?.Invoke(this, EventArgs.Empty); }); }
public void OnDownload(string url, string suggestedName, long totalSize, IWebDownloader downloader) { Logging.Write(url); ActionExtension.InvokeInMainThread(() => { new TemporaryFactoryAndLoader(url).RunAsync(suggestedName, totalSize, downloader).Ignore(); }); }
private void OnFrameLoadStart(object sender, FrameLoadStartEventArgs e) { if (e.Frame.IsMain) { ActionExtension.InvokeInMainThread(() => PageLoadingStarted?.Invoke(this, new UrlEventArgs(e.Url ?? string.Empty))); } }
public override string AcApiRequest(string url) { url = url.SubstringExt(AcApiHandlerFactory.AcSchemeName.Length + 3); Logging.Debug(url); var index = url.IndexOf('?'); var pieces = (index == -1 ? url : url.Substring(0, index)).Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); switch (pieces[0]) { case "getguid": return(SteamIdHelper.Instance.Value); case "setsetting": switch (pieces.ArrayElementAtOrDefault(1)) { case "race": foreach (var parameter in GetParameters()) { var p = parameter.Key.Split('/'); if (p.Length != 2) { Logging.Warning($"Invalid key: {parameter.Key}"); } else { Logging.Debug($"Parameter: {parameter.Key}={parameter.Value}"); _raceConfig[p[0]].Set(p[1], parameter.Value); } } break; default: Logging.Warning($"Unknown setting: {pieces.ArrayElementAtOrDefault(1)}"); break; } return(string.Empty); case "start": ActionExtension.InvokeInMainThread(() => { GameWrapper.StartAsync(new Game.StartProperties { PreparedConfig = _raceConfig }); }); return(string.Empty); default: Logging.Warning($"Unknown request: {pieces[0]} (“{url}”)"); return(null); } Dictionary <string, string> GetParameters() { return((index == -1 ? "" : url.Substring(index + 1)) .Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.Split(new[] { '=' }, 2)).ToDictionary( x => Uri.UnescapeDataString(x[0]), x => Uri.UnescapeDataString(x.ArrayElementAtOrDefault(1) ?? ""))); } }
private void ApplyDynamicBackground([CanBeNull] string filename, double opacity = 0.5) { ActionExtension.InvokeInMainThreadAsync(() => { try { if (filename == null) { DisposeHelper.Dispose(ref _dynamicBackground); if (FancyBackgroundManager.Instance.Enabled) { FancyBackgroundManager.Instance.Recreate(this); } else { ClearValue(BackgroundContentProperty); } } else { var animatedBackground = Regex.IsMatch(filename, @"\.(?:avi|flv|gif|m(?:4[pv]|kv|ov|p[4g])|og[vg]|qt|webm|wmv)$", RegexOptions.IgnoreCase) ? filename : null; var staticBackground = animatedBackground == null ? filename : Regex.Replace(filename, @"\.\w+$", @".jpg"); _dynamicBackground?.Dispose(); BackgroundContent = _dynamicBackground = new DynamicBackground { Animated = animatedBackground, Static = staticBackground, Opacity = opacity }; } } catch (Exception e) { Logging.Error(e); } }); }
public static void Reload() { _configs.Clear(); _featureSupported.Clear(); _installed.Reset(); ActionExtension.InvokeInMainThreadAsync(() => { Reloaded?.Invoke(null, EventArgs.Empty); }); }
public void prepareSkinAsync(string carId, string skinChecksum, string skinUrl, IJavascriptCallback callback) { ActionExtension.InvokeInMainThreadAsync(async() => { var car = await CarsManager.Instance.GetByIdAsync(carId); if (car == null) { callback?.ExecuteAsync($"Car with ID={carId} is missing"); return; } var cacheDirectory = FilesStorage.Instance.GetTemporaryDirectory("RaceU", "Skins", carId); var destinationFilename = Path.Combine(cacheDirectory, skinChecksum); if (File.Exists(destinationFilename)) { callback?.ExecuteAsync(null); return; } try { var data = await HttpClientHolder.Get().GetByteArrayAsync(skinUrl); await FileUtils.WriteAllBytesAsync(destinationFilename, data); } catch (Exception e) { callback?.ExecuteAsync($"Failed to download skin: {e.Message}"); return; } callback?.ExecuteAsync(null); }); }
public void startOnlineRace(string ip, int port, int httpPort, IJavascriptCallback callback = null) { if (_car == null) { throw new Exception("Car is not set"); } if (_track == null) { throw new Exception("Track is not set"); } ActionExtension.InvokeInMainThread(async() => { var result = await GameWrapper.StartAsync(new Game.StartProperties { BasicProperties = new Game.BasicProperties { CarId = _car.Id, TrackId = _track.MainTrackObject.Id, TrackConfigurationId = _track.LayoutId, CarSkinId = _carSkin?.Id ?? _car.SelectedSkin?.Id ?? "" }, ModeProperties = new Game.OnlineProperties { Guid = SteamIdHelper.Instance.Value, ServerIp = ip, ServerPort = port, ServerHttpPort = httpPort, Password = InternalUtils.GetRaceUPassword(_track.IdWithLayout, ip, port), RequestedCar = _car.Id } }); callback?.ExecuteAsync(result?.IsNotCancelled); }).Ignore(); }
private static async Task <ArgumentHandleResult> ProcessGoogleSpreadsheetsLocale(string id, [CanBeNull] string locale, bool around) { if (string.IsNullOrWhiteSpace(id)) { throw new InformativeException(ToolsStrings.Common_IdIsMissing); } var url = around ? $@"{InternalUtils.MainApiDomain}/u/around?id={id}" : $@"https://docs.google.com/spreadsheets/d/{id}/export?format=xlsx&authuser=0"; await Task.Run(() => { if (File.Exists(LocaleHelper.GetGoogleSheetsFilename())) { FileUtils.Recycle(LocaleHelper.GetGoogleSheetsFilename()); FileUtils.TryToDelete(LocaleHelper.GetGoogleSheetsFilename()); } }); await LoadRemoteFileToNew(url, LocaleHelper.GetGoogleSheetsFilename()); SettingsHolder.Locale.LoadUnpacked = true; if (locale != null) { SettingsHolder.Locale.LocaleName = locale; } ActionExtension.InvokeInMainThreadAsync(() => { if (ModernDialog.ShowMessage(AppStrings.CustomLocalesUpdated_Message, AppStrings.CustomLocalesUpdated_Title, MessageBoxButton.YesNo) == MessageBoxResult.Yes) { WindowsHelper.RestartCurrentApplication(); } }); return(ArgumentHandleResult.Successful); }
private void OnFrameLoadEnd(object sender, FrameLoadEndEventArgs e) { if (e.Frame.IsMain) { ActionExtension.InvokeInMainThread(() => PageLoaded?.Invoke(this, new UrlEventArgs(AlterUrl(e.Url)))); } }
private async Task AsyncAction() { Debug.WriteLine("ACMGR: WatchingTask.AsyncAction()"); while (_delay) { _delay = false; Debug.WriteLine("ACMGR: WatchingTask.AsyncAction() Delay"); int delayAmount; lock (_queue) { delayAmount = _queue.Any() && _queue.Peek().Type == WatcherChangeTypes.Deleted ? 300 : 200; } await Task.Delay(delayAmount); } ActionExtension.InvokeInMainThread(() => { try { Debug.WriteLine("ACMGR: WatchingTask.AsyncAction() Invoke"); // in some cases (CREATED, DELETED) queue could be cleared lock (_queue) { if (_queue.Any()) { var change = _queue.Dequeue(); _applier.ApplyChange(_location, change); if (_queue.Any()) { if (change.Type == WatcherChangeTypes.Changed) { // very special case: // after CHANGED could be only CHANGED, and only with FULL_FILENAME // let’s process all of them in one INVOKE foreach (var next in _queue) { _applier.ApplyChange(_location, next); } _queue.Clear(); } else { Debug.WriteLine("ACMGR: WatchingTask.AsyncAction() Next"); AsyncAction().Ignore(); return; } } } } _delay = false; _actionInProcess = false; } catch (Exception e) { Logging.Error(e); } }); }
private void OnFrameLoadStart(object sender, FrameLoadStartEventArgs e) { _inner.SetZoomLevel(Math.Log(_zoomLevel, 1.2)); if (e.Frame.IsMain) { ActionExtension.InvokeInMainThread(() => PageLoadingStarted?.Invoke(this, new UrlEventArgs(AlterUrl(e.Url)))); } }
private void OnPatchUpdaterPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(PatchUpdater.NothingAtAll)) { ActionExtension.InvokeInMainThreadAsync(() => UpdateContentTranslate(true)); } ActionExtension.InvokeInMainThreadAsync(() => Model.OnPatchUpdaterChanged(sender, e)); }
private static TaskbarProgress ValueFactory() { return(ActionExtension.InvokeInMainThread(() => { var window = Application.Current?.MainWindow ?? Application.Current?.Windows.OfType <DpiAwareWindow>().FirstOrDefault(x => x.IsVisible && x.ShowInTaskbar); return window == null ? null : new TaskbarProgress(window); })); }
private void OnFrameLoadStart(object sender, FrameLoadStartEventArgs e) { if (e.Frame.IsMain) { ActionExtension.InvokeInMainThreadAsync(() => { Navigating?.Invoke(this, PageLoadingEventArgs.Indetermitate); }); } }
protected override Task <bool> FixAsync(CarObject car, IProgress <AsyncProgressEntry> progress = null, CancellationToken cancellation = default(CancellationToken)) { progress?.Report(AsyncProgressEntry.FromStringIndetermitate("Fixing car…")); var data = car.AcdData; if (data == null || data.IsEmpty) { return(Task.FromResult(false)); } Lut torque, power; try { torque = TorquePhysicUtils.LoadCarTorque(data); power = TorquePhysicUtils.TorqueToPower(torque); } catch (Exception e) { Logging.Error(e); return(Task.FromResult(false)); } var multipler = ActionExtension.InvokeInMainThread(() => { var dlg = new CarTransmissionLossSelector(car, torque.MaxY, power.MaxY); dlg.ShowDialog(); return(dlg.IsResultOk ? dlg.Multipler : (double?)null); }); if (!multipler.HasValue) { return(Task.FromResult(false)); } torque.TransformSelf(x => x.Y * multipler.Value); power.TransformSelf(x => x.Y * multipler.Value); if (car.SpecsTorqueCurve != null) { var torqueUi = new Lut(car.SpecsTorqueCurve.Points); torqueUi.TransformSelf(x => x.Y * multipler.Value); car.SpecsTorqueCurve = new GraphData(torqueUi); } if (car.SpecsPowerCurve != null) { var powerUi = new Lut(car.SpecsPowerCurve.Points); powerUi.TransformSelf(x => x.Y * multipler.Value); car.SpecsPowerCurve = new GraphData(powerUi); } car.SpecsTorque = SelectedAcObjectViewModel.SpecsFormat(AppStrings.CarSpecs_Torque_FormatTooltip, torque.MaxY.ToString(@"F0", CultureInfo.InvariantCulture)) + (multipler.Value == 1d ? "*" : ""); car.SpecsBhp = SelectedAcObjectViewModel.SpecsFormat(multipler.Value == 1d ? AppStrings.CarSpecs_PowerAtWheels_FormatTooltip : AppStrings.CarSpecs_Power_FormatTooltip, power.MaxY.ToString(@"F0", CultureInfo.InvariantCulture)); return(Task.FromResult(true)); }
public void SetUp() { this.actionExtension = new ActionExtension("MethodName"); this.provideValueTarget = new Mock <IProvideValueTarget>(); this.provideValueTarget.Setup(x => x.TargetObject).Returns(new FrameworkElement()); this.serviceProvider = new Mock <IServiceProvider>(); serviceProvider.Setup(x => x.GetService(typeof(IProvideValueTarget))).Returns(provideValueTarget.Object); }
private void SetTrackOutlineTexture([CanBeNull] string filename, [NotNull] string textureName, [CanBeNull] string textureEffect) { SaveExtraCmTexture(textureName, () => { if (filename == null || !File.Exists(filename)) { return(null); } return(ActionExtension.InvokeInMainThread(() => PrepareTexture(filename, textureEffect))); }); }
private void ApplyTexture(Action <IPaintShopRenderer> action) { ActionExtension.InvokeInMainThreadAsync(() => { var renderer = _renderer; if (renderer != null) { action(_renderer); } }); }
private void SetThemeDynamicBackgroundListener() { UpdateThemeDynamicBackground(); AppearanceManager.Current.PropertyChanged += (sender, args) => { if (args.PropertyName == nameof(AppearanceManager.CurrentThemeDictionary)) { ActionExtension.InvokeInMainThreadAsync(UpdateThemeDynamicBackground); } }; }
private async void Dispatch() { if (_dispatched) return; _dispatched = true; await Task.Delay(300); ActionExtension.InvokeInMainThreadAsync(() => { UpdateInternal?.Invoke(this, new EventArgs()); _dispatched = false; }); }
public static ServerInformationComplete[] TryToGetList(IProgress <int> progress = null) { if (SteamIdHelper.Instance.Value == null) { throw new InformativeException(ToolsStrings.Common_SteamIdIsMissing); } for (var i = 0; i < ServersNumber && ServerUri != null; i++) { if (progress != null) { var j = i; ActionExtension.InvokeInMainThread(() => { progress.Report(j); }); } var uri = ServerUri; var requestUri = $@"http://{uri}/lobby.ashx/list?guid={SteamIdHelper.Instance.Value}"; ServerInformationComplete[] parsed; try { var watch = Stopwatch.StartNew(); parsed = LoadList(requestUri, OptionWebRequestTimeout, ServerInformationComplete.Deserialize); Logging.Write($"{watch.Elapsed.TotalMilliseconds:F1} ms"); } catch (Exception e) { Logging.Warning(e); NextServer(); continue; } if (parsed.Length == 0) { return(parsed); } var ip = parsed[0].Ip; if (!ip.StartsWith(@"192")) { return(parsed); } for (var j = parsed.Length - 1; j >= 0; j--) { var p = parsed[j]; if (p.Ip != ip) { return(parsed); } } throw new InformativeException("Kunos server returned gibberish instead of list of servers", "Could it be that you’re using Steam ID without AC linked to it?"); } return(null); }
public void Do(Action a) { if (_invokeInUiThread) { ActionExtension.InvokeInMainThread(() => DoUi(a)); } else { DoUi(a); } }
public void Set(TaskbarState state, double value) { ActionExtension.InvokeInMainThreadAsync(() => { if (state != _state || value != _value) { _state = state; _value = value; TaskbarService.Update(); } }); }
public void uploadCarSkinLiveryIconAsync(string carId, string skinId, string endpoint, IJavascriptCallback callback) { ActionExtension.InvokeInMainThreadAsync(async() => { var skin = await GetSkinAsync(carId, skinId, callback); if (skin == null) { return; } await UploadBinaryDataAsync(endpoint, () => FileUtils.ReadAllBytesAsync(skin.LiveryImage), callback); }); }