private void OnFrameLoadStart(object sender, FrameLoadStartEventArgs e) { if (e.Frame.IsMain) { ActionExtension.InvokeInMainThread(() => PageLoadingStarted?.Invoke(this, new UrlEventArgs(e.Url ?? string.Empty))); } }
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(); }
public void OnDownload(string url, string suggestedName, long totalSize, IWebDownloader downloader) { Logging.Write(url); ActionExtension.InvokeInMainThread(() => { new TemporaryFactoryAndLoader(url).RunAsync(suggestedName, totalSize, downloader).Ignore(); }); }
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); }
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); } }); } }
private void OnFrameLoadEnd(object sender, FrameLoadEndEventArgs e) { if (e.Frame.IsMain) { ActionExtension.InvokeInMainThread(() => PageLoaded?.Invoke(this, new UrlEventArgs(AlterUrl(e.Url)))); } }
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 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 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) { _inner.SetZoomLevel(Math.Log(_zoomLevel, 1.2)); if (e.Frame.IsMain) { ActionExtension.InvokeInMainThread(() => PageLoadingStarted?.Invoke(this, new UrlEventArgs(AlterUrl(e.Url)))); } }
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)); }
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))); }); }
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); } }
private void OnFrameLoadEnd(object sender, FrameLoadEndEventArgs e) { if (e.Frame.IsMain) { ActionExtension.InvokeInMainThread(() => { Navigating?.Invoke(this, PageLoadingEventArgs.Ready); ModifyPage(); Navigated?.Invoke(this, new PageLoadedEventArgs(_inner.Address)); }); } }
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case nameof(_renderer.AmbientShadowSizeChanged): ActionExtension.InvokeInMainThread(() => { _sizeSaveCommand?.RaiseCanExecuteChanged(); _sizeResetCommand?.RaiseCanExecuteChanged(); }); break; } }
protected virtual void OnRendererPropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case nameof(Renderer.CarSlots): ActionExtension.InvokeInMainThread(() => { UpdateSlots(); SaveLater(); }); break; } }
public static string GetText() { return(ActionExtension.InvokeInMainThread(() => { for (var i = 0; i < 5; i++) { try { return Clipboard.GetText(); } catch { Thread.Sleep(10); } } return null; })); }
public void CheckDisconnected() { foreach (var item in Leaderboard) { if (item.Driver != null && ++item.SilentFor > 5) { // Logging.Debug("item.SilentFor=" + item.SilentFor); ActionExtension.InvokeInMainThread(() => { item.Driver = null; item.Reset(true); ConnectedOnly.Refresh(item); }); } } }
public CmTexturesScriptTexture(Table v, [CanBeNull] ExtraDataProvider data, [NotNull] RaceTexturesContext texturesContext, [NotNull] Action <string, byte[]> saveCallback) { _data = data; _texturesContext = texturesContext; _saveCallback = saveCallback; _scale = v[@"scale"].As(1d); ActionExtension.InvokeInMainThread(() => { _canvas = new Cell { Width = v[@"width"].As(256d), Height = v[@"height"].As(256d), Background = new SolidColorBrush(GetColor(v, "background", Colors.Transparent)) }; }); }
private async void Update() { if (!IsLoaded || !_dirty || _busy) return; _busy = true; try { var carId = CarId; var trackAcId = TrackId?.Replace('/', '-'); var singleEntryMode = carId != null && TrackId != null; SetValue(SingleEntryModePropertyKey, singleEntryMode); SetValue(LoadingPropertyKey, true); await LapTimesManager.Instance.UpdateAsync(); if (singleEntryMode) { var entry = LapTimesManager.Instance.Entries.FirstOrDefault(x => x.CarId == carId && x.TrackAcId == trackAcId); _lapTimes.ReplaceEverythingBy_Direct(entry == null ? new LapTimeWrapped[0] : new[] { new LapTimeWrapped(entry) }); } else { var enumerable = LapTimesManager.Instance.Entries.Where(x => (carId == null || x.CarId == carId) && (trackAcId == null || x.TrackAcId == trackAcId)); switch (Order) { case BestLapsOrder.MostDrivenFirst: enumerable = enumerable.OrderByDescending(x => PlayerStatsManager.Instance.GetDistanceDrivenAtTrackAcId(x.TrackAcId)); break; case BestLapsOrder.FastestFirst: enumerable = enumerable.OrderBy(x => x.LapTime); break; default: throw new ArgumentOutOfRangeException(); } _lapTimes.ReplaceEverythingBy_Direct(enumerable.Take(Limit).Select(x => new LapTimeWrapped(x))); } } catch (Exception e) { Logging.Error(e); } finally { _dirty = false; _busy = false; ActionExtension.InvokeInMainThread(() => SetValue(LoadingPropertyKey, false)); } }
private void AddTrayIconWpf() { ActionExtension.InvokeInMainThread(() => { var patchSettings = SettingsShadersPatch.IsCustomShadersPatchInstalled() ? new MenuItem { Header = "Custom Shaders Patch settings", Command = SettingsShadersPatch.GetShowSettingsCommand() } : null; if (patchSettings != null) { LimitedService.SetLimited(patchSettings, true); } var rhm = RhmService.Instance.Active ? new MenuItem { Header = "RHM settings", Command = RhmService.Instance.ShowSettingsCommand } : null; var restore = new MenuItem { Header = UiStrings.Restore }; var close = new MenuItem { Header = UiStrings.Close }; restore.Click += OnRestoreMenuItemClick; close.Click += OnCloseMenuItemClick; _icon = new TaskbarIcon { Icon = AppIconService.GetTrayIcon(), ToolTipText = AppStrings.Hibernate_TrayText, ContextMenu = new ContextMenu() .AddItem(patchSettings) .AddItem(rhm) .AddSeparator() .AddItem(restore) .AddItem(close), DoubleClickCommand = new DelegateCommand(WakeUp) }; }); }
private async void OnDirectoryWatcher(object sender, FileSystemEventArgs e) { if (_updating || _saving) { return; } _updating = true; try { await Task.Delay(300); if (_updating) { ActionExtension.InvokeInMainThread(() => { SavedDrivers.ReplaceIfDifferBy(ServerSavedDriver.Load(DriversFilename)); }); await Task.Delay(200); } } finally { _updating = false; } }
private async Task RunAcServer(string serverExecutable, ICollection <string> log, IProgress <AsyncProgressEntry> progress, CancellationToken cancellation) { try { using (var process = new Process { StartInfo = { FileName = serverExecutable, Arguments = $"-c presets/{Id}/server_cfg.ini -e presets/{Id}/entry_list.ini", UseShellExecute = false, WorkingDirectory = Path.GetDirectoryName(serverExecutable) ?? "", RedirectStandardOutput = true, CreateNoWindow = true, RedirectStandardError = true, StandardOutputEncoding = Encoding.UTF8, StandardErrorEncoding = Encoding.UTF8, } }) { process.Start(); SetRunning(process); ChildProcessTracker.AddProcess(process); progress?.Report(AsyncProgressEntry.Finished); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.OutputDataReceived += (sender, args) => ActionExtension.InvokeInMainThread(() => log.Add(args.Data)); process.ErrorDataReceived += (sender, args) => ActionExtension.InvokeInMainThread(() => log.Add($@"[color=#ff0000]{args.Data}[/color]")); await process.WaitForExitAsync(cancellation); if (!process.HasExitedSafe()) { process.Kill(); } log.Add($@"[CM] Stopped: {process.ExitCode}"); } } finally { SetRunning(null); } }
public void _startOnlineRace(string jsonParams, IJavascriptCallback callback = null) { var args = JObject.Parse(jsonParams); if (_car == null) { throw new Exception("Car is not set"); } if (_track == null) { throw new Exception("Track is not set"); } var ip = args.GetStringValueOnly("ip") ?? throw new Exception("“ip” parameter is missing"); var port = args.GetIntValueOnly("port") ?? throw new Exception("“port” parameter is missing"); var properties = 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 = args.GetIntValueOnly("httpPort") ?? throw new Exception("“httpPort” parameter is missing"), Password = args.GetStringValueOnly("password") ?? InternalUtils.GetRaceUPassword(_track.IdWithLayout, ip, port), RequestedCar = _car.Id, CspFeaturesList = args.GetStringValueOnly("cspFeatures"), CspReplayClipUploadUrl = args.GetStringValueOnly("cspReplayClipUploadUrl"), } }; ActionExtension.InvokeInMainThread(async() => { var result = await GameWrapper.StartAsync(properties); callback?.ExecuteAsync(result?.IsNotCancelled); }).Ignore(); }
public bool Image(Table v) { var data = _data?.Get(GetText(v, "name") ?? ""); if (data == null) { Logging.Warning($"Image not found: {GetText(v, "name")}"); return(false); } ActionExtension.InvokeInMainThread(() => { var image = new Image { Source = BetterImage.LoadBitmapSourceFromBytes(data).ImageSource, Stretch = v[@"stretch"].As(Stretch.Uniform), Effect = GetEffect(v[@"effect"]?.ToString()) }; ApplyParams(v, image); _canvas.Children.Add(image); }); return(true); }
private async void OnPresetsUpdated(object sender, EventArgs args) { if (_innerReloading) { return; } _innerReloading = true; try { await Task.Delay(200); ActionExtension.InvokeInMainThread(() => { RebuildPresetsList().Forget(); }); } catch (Exception e) { Logging.Warning("OnPresetsUpdated() exception: " + e); } finally { _innerReloading = false; } }
private static async Task ResetService() { var secondResponse = ActionExtension.InvokeInMainThread(() => MessageDialog.Show( "Would you like to reset FTH system to make sure changes are applied? Otherwise, you would need to restart Windows.[br][br]It’ll need to run this command:[br][mono]Rundll32.exe fthsvc.dll,FthSysprepSpecialize[/mono][br][br]Or, Content Manager can simply prepare a .bat-file for you to inspect and run manually. [url=\"https://docs.microsoft.com/en-us/windows/win32/win7appqual/fault-tolerant-heap\"]Learn more[/url].", "One more thing", new MessageDialogButton(MessageBoxButton.YesNo, MessageBoxResult.Yes) { [MessageBoxResult.Yes] = "Reset automatically", [MessageBoxResult.No] = "Prepare a .bat-file only" })); if (secondResponse == MessageBoxResult.Cancel) { return; } var filename = FilesStorage.Instance.GetTemporaryFilename("RunElevated", "FixFTH.bat"); File.WriteAllText(filename, @"@echo off :: More info: https://docs.microsoft.com/en-us/windows/win32/win7appqual/fault-tolerant-heap echo Running rundll32.exe fthsvc.dll,FthSysprepSpecialize... cd %windir%\system32 %windir%\system32\rundll32.exe fthsvc.dll,FthSysprepSpecialize echo Done pause"); if (secondResponse == MessageBoxResult.Yes) { var procRunDll32 = ProcessExtension.Start("explorer.exe", new[] { filename }, new ProcessStartInfo { Verb = "runas" }); await procRunDll32.WaitForExitAsync().ConfigureAwait(false); Logging.Debug("Done: " + procRunDll32.ExitCode); } else if (secondResponse == MessageBoxResult.No) { WindowsHelper.ViewFile(filename); } }
private async void ReloadLater() { if (IsReloading || IsSaving || DateTime.Now - _lastSaved < TimeSpan.FromSeconds(3)) { return; } IsReloading = true; await Task.Delay(200); if (!IsReloading) { return; } try { int i; for (i = 0; i < 5; i++) { try { Ini = new IniFile(Filename); break; } catch (Exception) { await Task.Delay(100); } } if (i == 5) { Logging.Warning("Can’t load config file: " + Path.GetFileName(Filename)); return; } IsLoading = true; ActionExtension.InvokeInMainThread(LoadFromIni); IsLoading = false; } finally { IsReloading = false; } }
public bool RunContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model, IRunContextMenuCallback callback) { callback.Dispose(); ActionExtension.InvokeInMainThread(() => { var menu = new ContextMenu { Items = { new MenuItem { Header = "Back", Command = new DelegateCommand(browser.GoBack, () => browser.CanGoBack) }, new MenuItem { Header = "Forward", Command = new DelegateCommand(browser.GoForward, () => browser.CanGoForward) }, new MenuItem { Header = "Refresh", Command = new DelegateCommand(() => browser.Reload(true)) }, new Separator(), new MenuItem { Header = "Select All", Command = new DelegateCommand(() => browser.FocusedFrame.SelectAll()) }, new MenuItem { Header = "Open Page In Default Browser", Command = new DelegateCommand <string>(WindowsHelper.ViewInBrowser), CommandParameter = frame.Url }, } }; menu.IsOpen = true; }); return(true); }