private void UpdateErrorMessage(string filename) { string url; var extension = Path.GetExtension(filename)?.Replace(@".", "").ToLowerInvariant(); switch (extension) { case ".ogv": url = @"https://xiph.org/dshow/"; break; case ".webm": url = @"https://tools.google.com/dlpage/webmmf/"; break; case null: case "": url = null; break; default: url = $@"https://google.com/search?q={extension}+windows+media+player+codec"; break; } ((BbCodeBlock)_switch.False).Text = string.Format( "Can’t play file. Make sure Windows Media Player is available and {0}required codec is installed{1}, or enable VLC plugin instead.", url == null ? "" : $@"[url={BbCodeBlock.EncodeAttribute(url)}]", url == null ? "" : @"[/url]"); }
private string IdToBb(string id, bool car = true) { const string searchIcon = "F1 M 42.5,22C 49.4036,22 55,27.5964 55,34.5C 55,41.4036 49.4036,47 42.5,47C 40.1356,47 37.9245,46.3435 36,45.2426L 26.9749,54.2678C 25.8033,55.4393 23.9038,55.4393 22.7322,54.2678C 21.5607,53.0962 21.5607,51.1967 22.7322,50.0251L 31.7971,40.961C 30.6565,39.0755 30,36.8644 30,34.5C 30,27.5964 35.5964,22 42.5,22 Z M 42.5,26C 37.8056,26 34,29.8056 34,34.5C 34,39.1944 37.8056,43 42.5,43C 47.1944,43 51,39.1944 51,34.5C 51,29.8056 47.1944,26 42.5,26 Z"; const string linkIcon = "F1 M 23.4963,46.1288L 25.0796,48.8712L 29.4053,50.0303L 33.519,47.6553L 34.8902,46.8636L 37.6326,45.2803L 38.4242,46.6515L 37.2652,50.9772L 30.4091,54.9356L 21.7577,52.6174L 18.591,47.1326L 20.9091,38.4811L 27.7652,34.5227L 32.0909,35.6818L 32.8826,37.053L 30.1402,38.6364L 28.769,39.428L 24.6553,41.803L 23.4963,46.1288 Z M 38.7348,28.1895L 45.5908,24.2311L 54.2423,26.5493L 57.409,32.0341L 55.0908,40.6856L 48.2348,44.6439L 43.9091,43.4848L 43.1174,42.1136L 45.8598,40.5303L 47.231,39.7386L 51.3446,37.3636L 52.5037,33.0379L 50.9204,30.2955L 46.5946,29.1364L 42.481,31.5114L 41.1098,32.3031L 38.3674,33.8864L 37.5757,32.5152L 38.7348,28.1895 Z M 33.9006,45.1496L 31.7377,44.5701L 30.5502,42.5133L 31.1298,40.3504L 42.0994,34.0171L 44.2623,34.5966L 45.4498,36.6534L 44.8702,38.8163L 33.9006,45.1496 Z"; if (!car) { id = Regex.Replace(id, @"-([^-]+)$", "/$1"); } var name = $@"“{BbCodeBlock.Encode(id)}”"; var typeLocalized = car ? ToolsStrings.AdditionalContent_Car : ToolsStrings.AdditionalContent_Track; var searchUrl = $"cmd://findmissing/{(car ? "car" : "track")}?param={id}"; var searchLink = string.Format(@"[url={0}][ico={1}]Look for missing {2} online[/ico][/url]", BbCodeBlock.EncodeAttribute(searchUrl), BbCodeBlock.EncodeAttribute(searchIcon), typeLocalized); var version = car ? GetRequiredCarVersion(id) : GetRequiredTrackVersion(); if (OptionIgnoreIndexIfServerProvidesSpecificVersion && version != null || (car ? !IndexDirectDownloader.IsCarAvailable(id) : !IndexDirectDownloader.IsTrackAvailable(id))) { return($@"{name} \[{searchLink}]"); } var downloadUrl = $"cmd://downloadmissing/{(car ? "car" : "track")}?param={(string.IsNullOrWhiteSpace(version) ? id : $@"{id}|{version}")}";
private void Driver_OnContextMenuButtonClick(object sender, ContextMenuButtonEventArgs e) { var driver = ((FrameworkElement)sender).DataContext as ServerEntry.CurrentDriver; if (driver == null) { return; } var menu = new ContextMenu(); foreach (var tag in ServerEntry.DriverTag.GetTags().OrderBy(x => x.DisplayName)) { var icon = TryFindResource(@"PlayerTagIcon") as Shape; icon?.SetBinding(Shape.FillProperty, new Binding { Source = tag, Path = new PropertyPath(nameof(tag.Color)), Converter = ColorPicker.ColorToBrushConverter }); var header = new BbCodeBlock(); header.SetBinding(BbCodeBlock.BbCodeProperty, new Binding { Source = tag, Path = new PropertyPath(nameof(tag.DisplayName)) }); var item = new MenuItem { Header = icon == null ? (FrameworkElement)header : new DockPanel { Children = { icon, header } }, IsChecked = driver.Tags.GetByIdOrDefault(tag.Id) != null, StaysOpenOnClick = true, IsCheckable = true }; item.Click += (o, args) => { (((MenuItem)o).IsChecked ? driver.AddTagCommand : driver.RemoveTagCommand).Execute(tag.Id); }; menu.Items.Add(item); } menu.AddSeparator(); menu.Items.Add(new MenuItem { Header = "New Tag…", Command = new DelegateCommand(() => { new OnlineNewDriverTag(driver).ShowDialog(); }) }); menu.Items.Add(new MenuItem { Header = "Edit Tags…", Command = new DelegateCommand(() => { new OnlineDriverTags().ShowDialog(); }) }); e.Menu = menu; }
public Task EnableMod(GenericMod mod) { return(_busy.Task(async() => { if (_enabler == null || mod.IsEnabled) { return; } var conflicts = await _enabler.CheckConflictsAsync(mod); if (conflicts.Length > 0 && ModernDialog.ShowMessage( conflicts.Select(x => $@"• “{Path.GetFileName(x.RelativeName)}” has already been altered by the “{x.ModName}” mod;") .JoinToString("\n").ToSentence () + $"\n\nEnabling {BbCodeBlock.Encode(mod.DisplayName)} may have adverse effects. Are you sure you want to enable this mod?", "Conflict", MessageBoxButton.YesNo, "genericMods.conflict") != MessageBoxResult.Yes) { return; } try { using (var waiting = WaitingDialog.Create("Enabling mod…")) { await _enabler.EnableAsync(mod, waiting, waiting.CancellationToken); Changed?.Invoke(this, EventArgs.Empty); if (waiting.CancellationToken.IsCancellationRequested) { waiting.Report(AsyncProgressEntry.FromStringIndetermitate("Cancellation…")); await _enabler.DisableAsync(mod); } } } catch (Exception e) { NonfatalError.Notify("Can’t enable mod", e); } })); }
public override void OnApplyTemplate() { if (_carsPanel != null) { _carsPanel.MouseEnter -= CarsPanel_MouseEnter; } if (_carsPanel != null) { _sessionsPanel.MouseEnter -= SessionsPanel_MouseEnter; } if (_trackNameText != null) { _trackNameText.MouseEnter -= TrackNameText_MouseEnter; } if (_clientsText != null) { _clientsText.MouseEnter -= ClientsText_MouseEnter; } base.OnApplyTemplate(); _passwordIcon = (FrameworkElement)GetTemplateChild(@"PasswordIcon"); _bookedIcon = (FrameworkElement)GetTemplateChild(@"BookedForPlayerIcon"); _friendsIcon = (FrameworkElement)GetTemplateChild(@"FriendsIcon"); _hasErrorsGroup = (BooleanSwitch)GetTemplateChild(@"HasErrorsGroup"); _errorMessageGroup = (BbCodeBlock)GetTemplateChild(@"ErrorMessageGroup"); _pingText = (TextBlock)GetTemplateChild(@"PingText"); _clientsText = (TextBlock)GetTemplateChild(@"DisplayClientsText"); _timeLeftText = (TextBlock)GetTemplateChild(@"TimeLeftText"); _countryFlagImage = (Image)GetTemplateChild(@"CountryFlagImage"); _nameText = (TextBlock)GetTemplateChild(@"DisplayNameText"); _trackNameText = (TextBlock)GetTemplateChild(@"TrackNameText"); _countryName = (TextBlock)GetTemplateChild(@"CountryName"); _sessionsPanel = (Panel)GetTemplateChild(@"SessionsPanel"); _carsPanel = (Panel)GetTemplateChild(@"CarsPanel"); Update(Server); if (_carsPanel != null) { _carsPanel.MouseEnter += CarsPanel_MouseEnter; } if (_sessionsPanel != null) { _sessionsPanel.MouseEnter += SessionsPanel_MouseEnter; } if (_trackNameText != null) { _trackNameText.MouseEnter += TrackNameText_MouseEnter; } if (_clientsText != null) { _clientsText.MouseEnter += ClientsText_MouseEnter; } }
private void OnClosing(object sender, CancelEventArgs e) { if (_closed) { return; } try { if (ServerPresetsManager.Instance.IsScanned) { var running = ServerPresetsManager.Instance.Loaded.Where(x => x.IsRunning).ToList(); if (running.Count > 0 && ModernDialog.ShowMessage( $@"{"If you’ll close app, running servers will be stopped as well. Are you sure?"}{Environment.NewLine}{Environment.NewLine}{ running.Select(x => $@" • {BbCodeBlock.Encode(x.DisplayName)}").JoinToString(Environment.NewLine)}", "Some servers are running", MessageBoxButton.YesNo) != MessageBoxResult.Yes) { e.Cancel = true; return; } } if (ContentInstallationManager.Instance.HasUnfinishedItems && ModernDialog.ShowMessage( "If you’ll close app, installation will be terminated. Are you sure?", "Something is being installed", MessageBoxButton.YesNo) != MessageBoxResult.Yes) { e.Cancel = true; return; } var unsaved = Superintendent.Instance.UnsavedChanges(); if (unsaved.Count > 0) { switch (ModernDialog.ShowMessage( $@"{AppStrings.Main_UnsavedChanges}{Environment.NewLine}{Environment.NewLine}{ unsaved.OrderBy(x => x).Select(x => $@" • {x}").JoinToString(Environment.NewLine)}", AppStrings.Main_UnsavedChangesHeader, MessageBoxButton.YesNoCancel)) { case MessageBoxResult.Yes: Superintendent.Instance.SaveAll(); break; case MessageBoxResult.Cancel: e.Cancel = true; return; } } // Just in case, temporary _closed = true; Application.Current.Shutdown(); } catch (Exception ex) { Logging.Warning(ex); } }
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"), }); }
private static FrameworkElement ToBbCodeBlock(BbCodeBlock original) { var p = new BbCodeBlock { Text = original.Text, FontSize = original.FontSize, FontWeight = original.FontWeight, VerticalAlignment = VerticalAlignment.Center, TextAlignment = TextAlignment.Center }; p.SetValue(TextOptions.TextFormattingModeProperty, TextFormattingMode.Ideal); return(p); }
private static FrameworkElement ToBbCodeBlock(string text, int?decodeWidth) { var p = new BbCodeBlock { Text = text, FontSize = (decodeWidth ?? 60d) / 2, FontWeight = decodeWidth < 20 ? FontWeights.Bold : decodeWidth < 40 ? FontWeights.Normal : FontWeights.UltraLight, VerticalAlignment = VerticalAlignment.Center, TextAlignment = TextAlignment.Center }; p.SetValue(TextOptions.TextFormattingModeProperty, TextFormattingMode.Ideal); return(p); }
public OnlineItem() { Height = 60d; Background = new SolidColorBrush(Colors.Transparent); RenderOptions.SetBitmapScalingMode(this, BitmapScalingMode.LowQuality); _name = new BbCodeBlock { FontSize = 16d, FontWeight = FontWeights.Normal, TextWrapping = TextWrapping.NoWrap, TextTrimming = TextTrimming.CharacterEllipsis, Margin = new Thickness(22, 2, 116, 32), Mode = EmojiSupport.WithoutBbCodes }; Children.Add(_name); }
public static string GetVersionInfoDisplay([NotNull] this IAcObjectFullAuthorshipInformation obj) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if (obj.Version == null && obj.Author == null) { return(obj.Url != null ? $@"[url={BbCodeBlock.EncodeAttribute(obj.Url)}]{BbCodeBlock.Encode(obj.Url)}[/url]" : null); } var result = obj.Author == null ? obj.Version : obj.Version == null ? obj.Author : $"{obj.Author} ({obj.Version})"; return(obj.Url != null ? $@"[url={BbCodeBlock.EncodeAttribute(obj.Url)}]{BbCodeBlock.Encode(result)}[/url]" : result); }
public static void Initialize() { BbCodeBlock.AddLinkCommand(new Uri("cmd://workshop/showCarInShowroom"), new AsyncCommand <string>(ShowCarInShowroomAsync)); BbCodeBlock.AddLinkCommand(new Uri("cmd://workshop/editUserProfile"), new AsyncCommand <string>(async userId => { try { var client = WorkshopHolder.Client; var model = WorkshopHolder.Model; var userUrl = $@"/users/{userId ?? @"~me"}"; var currentProfile = await client.GetAsync <UserInfo>(userUrl); if (await new WorkshopEditProfile(client, currentProfile).ShowDialogAsync() == true) { model.AuthorizedAs = await client.GetAsync <UserInfo>(userUrl); } } catch (Exception e) { NonfatalError.Notify("Failed to edit profile", e); } })); }
private static string PrepareLicense(string source) { return(Regex.Replace(BbCodeBlock.Encode(source), @"https?://\S+", x => { var last = x.Value[x.Value.Length - 1]; string url, postfix; if (last == '.' || last == ';' || last == ')' || last == ',') { url = x.Value.Substring(0, x.Value.Length - 1); postfix = last.ToString(); } else { url = x.Value; postfix = ""; } return $"[url={BbCodeBlock.EncodeAttribute(BbCodeBlock.Decode(url))}]{url}[/url]{postfix}"; })); }
private Prompt(string title, string description, string defaultValue, string placeholder, string toolTip, bool multiline, bool passwordMode, bool required, int maxLength, IEnumerable <string> suggestions, bool suggestionsFixed, string comment, Func <string, Task <IEnumerable <string> > > suggestionsCallback = null, Func <string, Task <string> > verificationCallback = null, bool suggestionsAsList = false) { DataContext = new ViewModel(description, defaultValue, placeholder, toolTip, required) { SuggestionsCallback = suggestionsCallback, VerificationCallback = verificationCallback, }; if (Model.SuggestionsCallback != null) { Model.UpdateSuggestionsAsync().Ignore(); } InitializeComponent(); Buttons = new[] { OkButton, CancelButton }; _multiline = multiline; var suggestionsList = new Lazy <List <string> >(suggestions.ToList); if (required) { OkButton.SetBinding(IsEnabledProperty, new Binding { Source = DataContext, Path = new PropertyPath(nameof(ViewModel.Text)), Converter = this }); } if (comment != null) { ButtonsRowContent = new BbCodeBlock { Text = comment, Style = (Style)FindResource(@"BbCodeBlock.Small") }; ButtonsRowContentAlignment = HorizontalAlignment.Left; } Title = title; FrameworkElement element; if (passwordMode) { var passwordBox = new ProperPasswordBox(); passwordBox.SetBinding(ProperPasswordBox.PasswordProperty, new Binding { Source = DataContext, Path = new PropertyPath(nameof(ViewModel.Text)), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged }); element = passwordBox; } else if (suggestions != null || suggestionsCallback != null) { var comboBox = new BetterComboBox { IsEditable = !suggestionsFixed, IsTextSearchEnabled = true }; if (suggestions is INotifyCollectionChanged) { comboBox.SetBinding(ItemsControl.ItemsSourceProperty, new Binding { Source = suggestions }); } else if (suggestions != null) { comboBox.ItemsSource = suggestionsList.Value; } else { Model.SuggestionsDynamic = new BetterObservableCollection <string>(); comboBox.SetBinding(ItemsControl.ItemsSourceProperty, new Binding { Source = Model.SuggestionsDynamic }); } comboBox.SetBinding(ComboBox.TextProperty, new Binding { Source = DataContext, Path = new PropertyPath(nameof(ViewModel.Text)), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, ValidatesOnDataErrors = true }); if (placeholder != null) { comboBox.Placeholder = placeholder; } element = comboBox; } else { var textBox = new BetterTextBox(); textBox.SetBinding(TextBox.TextProperty, new Binding { Source = DataContext, Path = new PropertyPath(nameof(ViewModel.Text)), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, ValidatesOnDataErrors = true }); if (maxLength != -1) { textBox.MaxLength = maxLength; } if (multiline) { textBox.AcceptsReturn = true; textBox.TextWrapping = TextWrapping.Wrap; textBox.Height = 240; } if (placeholder != null) { textBox.Placeholder = placeholder; } element = textBox; } Panel.Children.Add(element); if (suggestionsAsList) { var listBox = new ListBox { IsTextSearchEnabled = true, Height = 200 }; if (suggestions is INotifyCollectionChanged) { listBox.SetBinding(ItemsControl.ItemsSourceProperty, new Binding { Source = suggestions }); } else if (suggestions != null) { listBox.ItemsSource = suggestionsList.Value; } else { if (Model.SuggestionsDynamic == null) { Model.SuggestionsDynamic = new BetterObservableCollection <string>(); } listBox.SetBinding(ItemsControl.ItemsSourceProperty, new Binding { Source = Model.SuggestionsDynamic }); } listBox.SetBinding(Selector.SelectedItemProperty, new Binding { Source = DataContext, Path = new PropertyPath(nameof(ViewModel.TextInList)), Mode = BindingMode.TwoWay }); Panel.Children.Add(listBox); } if (toolTip != null) { element.SetValue(ToolTipProperty, toolTip); } PreviewKeyDown += OnKeyDown; element.PreviewKeyDown += OnKeyDown; _element = element; Closing += (sender, args) => { if (MessageBoxResult != MessageBoxResult.OK) { return; } Result = Model.Text; }; }
private static string BbCodeIcon([Localizable(false)] string icon, [Localizable(false)] string command, string hint) { return($@"[url={BbCodeBlock.EncodeAttribute(command)}][ico={BbCodeBlock.EncodeAttribute(icon)}]{BbCodeBlock.Encode(hint)}[/ico][/url]"); }
private void Parse(Span span) { var context = new ParseContext(span); while (true) { var token = La(1); Consume(); switch (token.TokenType) { case BbCodeLexer.TokenStartTag: ParseTag(token.Value, true, context); break; case BbCodeLexer.TokenEndTag: ParseTag(token.Value, false, context); break; case BbCodeLexer.TokenText: var parent = span; { Uri uri; string parameter; string targetName; // parse uri value for optional parameter and/or target, eg [url=cmd://foo|parameter|target] if (NavigationHelper.TryParseUriWithParameters(context.NavigateUri, out uri, out parameter, out targetName)) { var link = new Hyperlink(); if (context.IconGeometry != null) { link.TextDecorations.Clear(); } // assign ICommand instance if available, otherwise set NavigateUri ICommand command; if (Commands != null && Commands.TryGetValue(uri, out command)) { link.Command = command; link.CommandParameter = parameter; if (targetName != null) { link.CommandTarget = _source?.FindName(targetName) as IInputElement; } } else { link.NavigateUri = uri; link.TargetName = parameter; } parent = link; span.Inlines.Add(parent); } } if (context.IconGeometry != null) { var icon = new Path { Stretch = Stretch.Uniform, Data = context.IconGeometry }; icon.SetBinding(Shape.FillProperty, new Binding { Path = new PropertyPath("(TextBlock.Foreground)"), RelativeSource = new RelativeSource(RelativeSourceMode.Self), }); Logging.Debug(token.Value); var border = new Border { Background = new SolidColorBrush(Colors.Transparent), Child = icon, ToolTip = new ToolTip { Content = new TextBlock { Text = token.Value } } }; border.SetBinding(FrameworkElement.HeightProperty, new Binding { Path = new PropertyPath("(TextBlock.FontSize)"), RelativeSource = new RelativeSource(RelativeSourceMode.Self), Converter = new MultiplyConverter(), ConverterParameter = 0.7 }); border.SetBinding(FrameworkElement.WidthProperty, new Binding { Path = new PropertyPath(nameof(Border.Height)), RelativeSource = new RelativeSource(RelativeSourceMode.Self) }); parent.Inlines.Add(new InlineUIContainer { Child = border }); continue; } { string uri; double maxSize; bool expand, toolTip; FileCache cache; if (context.ImageUri?.StartsWith(@"emoji://") == true) { maxSize = 0; expand = false; toolTip = false; var provider = BbCodeBlock.OptionEmojiProvider; if (provider == null) { uri = null; cache = null; } else { var emoji = context.ImageUri.Substring(8); uri = string.Format(provider, emoji); cache = BbCodeBlock.OptionEmojiCacheDirectory == null ? null : _emojiCache ?? (_emojiCache = new FileCache(BbCodeBlock.OptionEmojiCacheDirectory)); } } else { toolTip = true; Uri temporary; string parameter; string targetName; if (NavigationHelper.TryParseUriWithParameters(context.ImageUri, out temporary, out parameter, out targetName)) { uri = temporary.OriginalString; if (double.TryParse(parameter, out maxSize)) { expand = true; } else { maxSize = double.NaN; expand = false; } cache = BbCodeBlock.OptionImageCacheDirectory == null ? null : _imageCache ?? (_imageCache = new FileCache(BbCodeBlock.OptionImageCacheDirectory)); } else { uri = null; maxSize = double.NaN; expand = false; cache = null; } } if (uri != null) { FrameworkElement image = new Image(cache) { ImageUrl = uri }; if (toolTip) { image.ToolTip = new ToolTip { Content = new TextBlock { Text = token.Value } }; } if (double.IsNaN(maxSize)) { RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.LowQuality); } else { if (Equals(maxSize, 0d)) { image.SetBinding(FrameworkElement.MaxHeightProperty, new Binding { Path = new PropertyPath(nameof(TextBlock.FontSize)), RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(TextBlock), 1), Converter = new MultiplyConverter(), }); image.Margin = new Thickness(1, -1, 1, -1); } else { image.MaxWidth = maxSize; image.MaxHeight = maxSize; } RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.HighQuality); } if (expand) { image.Cursor = Cursors.Hand; image.MouseDown += (sender, args) => { args.Handled = true; BbCodeBlock.OnImageClicked(new BbCodeImageEventArgs(new Uri(uri, UriKind.RelativeOrAbsolute))); }; } var container = new InlineUIContainer { Child = image }; parent.Inlines.Add(container); continue; } } var run = context.CreateRun(token.Value); parent.Inlines.Add(run); break; case BbCodeLexer.TokenLineBreak: span.Inlines.Add(new LineBreak()); break; case BbCodeLexer.TokenAttribute: throw new ParseException(UiStrings.UnexpectedToken); case Lexer.TokenEnd: return; default: throw new ParseException(UiStrings.UnknownTokenType); } } }
private string GetBrokenSuggestions() { if (_something is CefSharpWrapper || _something is FormsCefSharpWrapper) { var directory = @"file://" + PluginsManager.Instance.GetPluginDirectory(KnownPlugins.CefSharp); return ($"Try to reinstall CefSharp plugin, its installation could be damaged. To do that, [url={BbCodeBlock.EncodeAttribute(directory)}]remove this directory[/url] (you’ll need to close the app to be able to remove it)."); } return(null); }
private App() { if (AppArguments.GetBool(AppFlag.IgnoreHttps)) { ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true; } AppArguments.Set(AppFlag.SyncNavigation, ref ModernFrame.OptionUseSyncNavigation); AppArguments.Set(AppFlag.DisableTransitionAnimation, ref ModernFrame.OptionDisableTransitionAnimation); AppArguments.Set(AppFlag.RecentlyClosedQueueSize, ref LinkGroupFilterable.OptionRecentlyClosedQueueSize); AppArguments.Set(AppFlag.NoProxy, ref KunosApiProvider.OptionNoProxy); var proxy = AppArguments.Get(AppFlag.Proxy); if (!string.IsNullOrWhiteSpace(proxy)) { try { var s = proxy.Split(':'); WebRequest.DefaultWebProxy = new WebProxy(s[0], FlexibleParser.ParseInt(s.ElementAtOrDefault(1), 1080)); } catch (Exception e) { Logging.Error(e); } } // TODO: AppArguments.Set(AppFlag.ScanPingTimeout, ref RecentManagerOld.OptionScanPingTimeout); AppArguments.Set(AppFlag.LanSocketTimeout, ref KunosApiProvider.OptionLanSocketTimeout); AppArguments.Set(AppFlag.LanPollTimeout, ref KunosApiProvider.OptionLanPollTimeout); AppArguments.Set(AppFlag.WebRequestTimeout, ref KunosApiProvider.OptionWebRequestTimeout); AppArguments.Set(AppFlag.DirectRequestTimeout, ref KunosApiProvider.OptionDirectRequestTimeout); AppArguments.Set(AppFlag.CommandTimeout, ref GameCommandExecutorBase.OptionCommandTimeout); AppArguments.Set(AppFlag.DisableAcRootChecking, ref AcRootDirectory.OptionDisableChecking); AppArguments.Set(AppFlag.AcObjectsLoadingConcurrency, ref BaseAcManagerNew.OptionAcObjectsLoadingConcurrency); AppArguments.Set(AppFlag.SkinsLoadingConcurrency, ref CarObject.OptionSkinsLoadingConcurrency); AppArguments.Set(AppFlag.KunosCareerIgnoreSkippedEvents, ref KunosCareerEventsManager.OptionIgnoreSkippedEvents); AppArguments.Set(AppFlag.IgnoreMissingSkinsInKunosEvents, ref KunosEventObjectBase.OptionIgnoreMissingSkins); AppArguments.Set(AppFlag.CanPack, ref AcCommonObject.OptionCanBePackedFilter); AppArguments.Set(AppFlag.CanPackCars, ref CarObject.OptionCanBePackedFilter); AppArguments.Set(AppFlag.ForceToastFallbackMode, ref Toast.OptionFallbackMode); AppArguments.Set(AppFlag.SmartPresetsChangedHandling, ref UserPresetsControl.OptionSmartChangedHandling); AppArguments.Set(AppFlag.EnableRaceIniRestoration, ref Game.OptionEnableRaceIniRestoration); AppArguments.Set(AppFlag.EnableRaceIniTestMode, ref Game.OptionRaceIniTestMode); AppArguments.Set(AppFlag.RaceOutDebug, ref Game.OptionDebugMode); AppArguments.Set(AppFlag.NfsPorscheTribute, ref RaceGridViewModel.OptionNfsPorscheNames); AppArguments.Set(AppFlag.KeepIniComments, ref IniFile.OptionKeepComments); AppArguments.Set(AppFlag.AutoConnectPeriod, ref OnlineServer.OptionAutoConnectPeriod); LimitedSpace.Initialize(); LimitedStorage.Initialize(); DataProvider.Initialize(); CountryIdToImageConverter.Initialize( FilesStorage.Instance.GetDirectory(FilesStorage.DataDirName, ContentCategory.CountryFlags), FilesStorage.Instance.GetDirectory(FilesStorage.DataUserDirName, ContentCategory.CountryFlags)); FilesStorage.Instance.Watcher(ContentCategory.CountryFlags).Update += (sender, args) => { CountryIdToImageConverter.ResetCache(); }; TestKey(); AppDomain.CurrentDomain.ProcessExit += OnProcessExit; if (!AppArguments.GetBool(AppFlag.PreventDisableWebBrowserEmulationMode) && ( ValuesStorage.GetInt(WebBrowserEmulationModeDisabledKey) < WebBrowserHelper.EmulationModeDisablingVersion || AppArguments.GetBool(AppFlag.ForceDisableWebBrowserEmulationMode))) { try { WebBrowserHelper.DisableBrowserEmulationMode(); ValuesStorage.Set(WebBrowserEmulationModeDisabledKey, WebBrowserHelper.EmulationModeDisablingVersion); } catch (Exception e) { Logging.Warning("Can’t disable emulation mode: " + e); } } JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.None, NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Include, Culture = CultureInfo.InvariantCulture }; AcToolsLogging.Logger = (s, m, p, l) => Logging.Write($"{s} (AcTools)", m, p, l); AcToolsLogging.NonFatalErrorHandler = (s, c, e) => NonfatalError.Notify(s, c, e); var ignoreControls = AppArguments.Get(AppFlag.IgnoreControls); if (!string.IsNullOrWhiteSpace(ignoreControls)) { ControlsSettings.OptionIgnoreControlsFilter = Filter.Create(new StringTester(), ignoreControls); } var sseStart = AppArguments.Get(AppFlag.SseName); if (!string.IsNullOrWhiteSpace(sseStart)) { SseStarter.OptionStartName = sseStart; } AppArguments.Set(AppFlag.SseLogging, ref SseStarter.OptionLogging); FancyBackgroundManager.Initialize(); if (AppArguments.Has(AppFlag.UiScale)) { DpiAwareWindow.OptionScale = AppArguments.GetDouble(AppFlag.UiScale, 1d); } if (!AppKeyHolder.IsAllRight) { AppAppearanceManager.OptionCustomThemes = false; } else { AppArguments.Set(AppFlag.CustomThemes, ref AppAppearanceManager.OptionCustomThemes); } AppArguments.Set(AppFlag.FancyHintsDebugMode, ref FancyHint.OptionDebugMode); AppArguments.Set(AppFlag.FancyHintsMinimumDelay, ref FancyHint.OptionMinimumDelay); /*AppAppearanceManager.OptionIdealFormattingModeDefaultValue = AppArguments.GetBool(AppFlag.IdealFormattingMode, * !Equals(DpiAwareWindow.OptionScale, 1d));*/ AppAppearanceManager.Initialize(); AcObjectsUriManager.Register(new UriProvider()); { var uiFactory = new GameWrapperUiFactory(); GameWrapper.RegisterFactory(uiFactory); ServerEntry.RegisterFactory(uiFactory); } GameWrapper.RegisterFactory(new DefaultAssistsFactory()); LapTimesManager.Instance.SetListener(); AcError.RegisterFixer(new AcErrorFixer()); AcError.RegisterSolutionsFactory(new SolutionsFactory()); InitializePresets(); SharingHelper.Initialize(); SharingUiHelper.Initialize(); { var addonsDir = FilesStorage.Instance.GetFilename("Addons"); var pluginsDir = FilesStorage.Instance.GetFilename("Plugins"); if (Directory.Exists(addonsDir) && !Directory.Exists(pluginsDir)) { Directory.Move(addonsDir, pluginsDir); } else { pluginsDir = FilesStorage.Instance.GetDirectory("Plugins"); } PluginsManager.Initialize(pluginsDir); PluginsWrappers.Initialize( new FmodPluginWrapper(), new MagickPluginWrapper(), new AwesomiumPluginWrapper(), new CefSharpPluginWrapper(), new StarterPlus()); } { var onlineMainListFile = FilesStorage.Instance.GetFilename("Online Servers", "Main List.txt"); var onlineFavouritesFile = FilesStorage.Instance.GetFilename("Online Servers", "Favourites.txt"); if (File.Exists(onlineMainListFile) && !File.Exists(onlineFavouritesFile)) { Directory.Move(onlineMainListFile, onlineFavouritesFile); } } SteamIdHelper.Initialize(AppArguments.Get(AppFlag.ForceSteamId)); Superintendent.Initialize(); AppArguments.Set(AppFlag.OfflineMode, ref AppKeyDialog.OptionOfflineMode); PrepareUi(); AppShortcut.Initialize("AcClub.ContentManager", "Content Manager"); AppIconService.Initialize(this); Toast.SetDefaultAction(() => (Current.Windows.OfType <ModernWindow>().FirstOrDefault(x => x.IsActive) ?? Current.MainWindow as ModernWindow)?.BringToFront()); BbCodeBlock.ImageClicked += OnBbImageClick; BbCodeBlock.OptionEmojiProvider = InternalUtils.GetEmojiProvider(); BbCodeBlock.OptionImageCacheDirectory = FilesStorage.Instance.GetTemporaryFilename("Images"); BbCodeBlock.OptionEmojiCacheDirectory = FilesStorage.Instance.GetTemporaryFilename("Emoji"); BbCodeBlock.AddLinkCommand(new Uri("cmd://findmissing/car"), new DelegateCommand <string>(id => { WindowsHelper.ViewInBrowser(SettingsHolder.Content.MissingContentSearch.GetUri(id, SettingsHolder.MissingContentType.Car)); })); BbCodeBlock.AddLinkCommand(new Uri("cmd://findmissing/track"), new DelegateCommand <string>(id => { WindowsHelper.ViewInBrowser(SettingsHolder.Content.MissingContentSearch.GetUri(id, SettingsHolder.MissingContentType.Track)); })); BbCodeBlock.AddLinkCommand(new Uri("cmd://downloadmissing/car"), new DelegateCommand <string>(id => { var s = id.Split('|'); IndexDirectDownloader.DownloadCarAsync(s[0], s.ElementAtOrDefault(1)).Forget(); })); BbCodeBlock.AddLinkCommand(new Uri("cmd://downloadmissing/track"), new DelegateCommand <string>(id => { var s = id.Split('|'); IndexDirectDownloader.DownloadTrackAsync(s[0], s.ElementAtOrDefault(1)).Forget(); })); BbCodeBlock.AddLinkCommand(new Uri("cmd://createneutrallut"), new DelegateCommand <string>(id => { NeutralColorGradingLut.CreateNeutralLut(id.AsInt(16)); })); BbCodeBlock.DefaultLinkNavigator.PreviewNavigate += (sender, args) => { if (args.Uri.IsAbsoluteUri && args.Uri.Scheme == "acmanager") { ArgumentsHandler.ProcessArguments(new[] { args.Uri.ToString() }).Forget(); args.Cancel = true; } }; AppArguments.SetSize(AppFlag.ImagesCacheLimit, ref BetterImage.OptionCacheTotalSize); AppArguments.Set(AppFlag.ImagesMarkCached, ref BetterImage.OptionMarkCached); BetterImage.RemoteUserAgent = CmApiProvider.UserAgent; BetterImage.RemoteCacheDirectory = BbCodeBlock.OptionImageCacheDirectory; AppArguments.Set(AppFlag.UseVlcForAnimatedBackground, ref DynamicBackground.OptionUseVlc); Filter.OptionSimpleMatching = SettingsHolder.Content.SimpleFiltering; CarBlock.CustomShowroomWrapper = new CustomShowroomWrapper(); CarBlock.CarSetupsView = new CarSetupsView(); var acRootIsFine = Superintendent.Instance.IsReady && !AcRootDirectorySelector.IsReviewNeeded(); if (acRootIsFine && SteamStarter.Initialize(AcRootDirectory.Instance.Value)) { if (SettingsHolder.Drive.SelectedStarterType != SettingsHolder.DriveSettings.SteamStarterType) { SettingsHolder.Drive.SelectedStarterType = SettingsHolder.DriveSettings.SteamStarterType; Toast.Show("Starter Changed to Replacement", "Enjoy Steam being included into CM"); } } else if (SettingsHolder.Drive.SelectedStarterType == SettingsHolder.DriveSettings.SteamStarterType) { SettingsHolder.Drive.SelectedStarterType = SettingsHolder.DriveSettings.OfficialStarterType; Toast.Show("Starter Changed to Official", "Steam Starter is unavailable", () => { ModernDialog.ShowMessage("To use Steam Starter, please make sure CM is taken place of the official launcher and AC root directory is valid.", "Steam Starter is unavailable", MessageBoxButton.OK); }); } InitializeUpdatableStuff(); BackgroundInitialization(); FatalErrorMessage.Register(this); ImageUtils.SafeMagickWrapper = fn => { try { return(fn()); } catch (OutOfMemoryException e) { NonfatalError.Notify(ToolsStrings.MagickNet_CannotLoad, ToolsStrings.MagickNet_CannotLoad_Commentary, e); } catch (Exception e) { NonfatalError.Notify(ToolsStrings.MagickNet_CannotLoad, e); } return(null); }; AbstractDataFile.ErrorsCatcher = new DataSyntaxErrorCatcher(); AppArguments.Set(AppFlag.SharedMemoryLiveReadingInterval, ref AcSharedMemory.OptionLiveReadingInterval); AcSharedMemory.Initialize(); AppArguments.Set(AppFlag.RunRaceInformationWebserver, ref PlayerStatsManager.OptionRunStatsWebserver); AppArguments.Set(AppFlag.RaceInformationWebserverFile, ref PlayerStatsManager.OptionWebserverFilename); PlayerStatsManager.Instance.SetListener(); // AppArguments.Set(AppFlag.RhmKeepAlive, ref RhmService.OptionKeepRunning); RhmService.Instance.SetListener(); _hibernator = new AppHibernator(); _hibernator.SetListener(); AppArguments.Set(AppFlag.TrackMapGeneratorMaxSize, ref TrackMapRenderer.OptionMaxSize); CommonFixes.Initialize(); // TODO: rearrange code! CmPreviewsSettings.SelectCarDialog = SelectCarDialog.Show; CmPreviewsTools.MissingShowroomHelper = new CarUpdatePreviewsDialog.MissingShowroomHelper(); // paint shop+livery generator? LiteShowroomTools.LiveryGenerator = new LiveryGenerator(); // auto-show that thing InstallAdditionalContentDialog.Initialize(); ShutdownMode = ShutdownMode.OnExplicitShutdown; new AppUi(this).Run(); }
private App() { if (AppArguments.GetBool(AppFlag.IgnoreHttps)) { ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true; } AppArguments.Set(AppFlag.SyncNavigation, ref ModernFrame.OptionUseSyncNavigation); AppArguments.Set(AppFlag.DisableTransitionAnimation, ref ModernFrame.OptionDisableTransitionAnimation); AppArguments.Set(AppFlag.RecentlyClosedQueueSize, ref LinkGroupFilterable.OptionRecentlyClosedQueueSize); AppArguments.Set(AppFlag.NoProxy, ref KunosApiProvider.OptionNoProxy); var proxy = AppArguments.Get(AppFlag.Proxy); if (!string.IsNullOrWhiteSpace(proxy)) { try { var s = proxy.Split(':'); WebRequest.DefaultWebProxy = new WebProxy(s[0], FlexibleParser.ParseInt(s.ArrayElementAtOrDefault(1), 1080)); } catch (Exception e) { Logging.Error(e); } } // TODO: AppArguments.Set(AppFlag.ScanPingTimeout, ref RecentManagerOld.OptionScanPingTimeout); AppArguments.Set(AppFlag.LanSocketTimeout, ref KunosApiProvider.OptionLanSocketTimeout); AppArguments.Set(AppFlag.LanPollTimeout, ref KunosApiProvider.OptionLanPollTimeout); AppArguments.Set(AppFlag.WebRequestTimeout, ref KunosApiProvider.OptionWebRequestTimeout); AppArguments.Set(AppFlag.DirectRequestTimeout, ref KunosApiProvider.OptionDirectRequestTimeout); AppArguments.Set(AppFlag.CommandTimeout, ref GameCommandExecutorBase.OptionCommandTimeout); AppArguments.Set(AppFlag.DisableAcRootChecking, ref AcPaths.OptionEaseAcRootCheck); AppArguments.Set(AppFlag.AcObjectsLoadingConcurrency, ref BaseAcManagerNew.OptionAcObjectsLoadingConcurrency); AppArguments.Set(AppFlag.SkinsLoadingConcurrency, ref CarObject.OptionSkinsLoadingConcurrency); AppArguments.Set(AppFlag.KunosCareerIgnoreSkippedEvents, ref KunosCareerEventsManager.OptionIgnoreSkippedEvents); AppArguments.Set(AppFlag.IgnoreMissingSkinsInKunosEvents, ref KunosEventObjectBase.OptionIgnoreMissingSkins); AppArguments.Set(AppFlag.CanPack, ref AcCommonObject.OptionCanBePackedFilter); AppArguments.Set(AppFlag.CanPackCars, ref CarObject.OptionCanBePackedFilter); AppArguments.Set(AppFlag.ForceToastFallbackMode, ref Toast.OptionFallbackMode); AppArguments.Set(AppFlag.SmartPresetsChangedHandling, ref UserPresetsControl.OptionSmartChangedHandling); AppArguments.Set(AppFlag.EnableRaceIniRestoration, ref Game.OptionEnableRaceIniRestoration); AppArguments.Set(AppFlag.EnableRaceIniTestMode, ref Game.OptionRaceIniTestMode); AppArguments.Set(AppFlag.RaceOutDebug, ref Game.OptionDebugMode); AppArguments.Set(AppFlag.NfsPorscheTribute, ref RaceGridViewModel.OptionNfsPorscheNames); AppArguments.Set(AppFlag.KeepIniComments, ref IniFile.OptionKeepComments); AppArguments.Set(AppFlag.AutoConnectPeriod, ref OnlineServer.OptionAutoConnectPeriod); AppArguments.Set(AppFlag.GenericModsLogging, ref GenericModsEnabler.OptionLoggingEnabled); AppArguments.Set(AppFlag.SidekickOptimalRangeThreshold, ref SidekickHelper.OptionRangeThreshold); AppArguments.Set(AppFlag.GoogleDriveLoaderDebugMode, ref GoogleDriveLoader.OptionDebugMode); AppArguments.Set(AppFlag.GoogleDriveLoaderManualRedirect, ref GoogleDriveLoader.OptionManualRedirect); AppArguments.Set(AppFlag.DebugPing, ref ServerEntry.OptionDebugPing); AppArguments.Set(AppFlag.DebugContentId, ref AcObjectNew.OptionDebugLoading); AppArguments.Set(AppFlag.JpegQuality, ref ImageUtilsOptions.JpegQuality); AppArguments.Set(AppFlag.FbxMultiMaterial, ref Kn5.OptionJoinToMultiMaterial); Acd.Factory = new AcdFactory(); Lazier.SyncAction = ActionExtension.InvokeInMainThreadAsync; KeyboardListenerFactory.Register <KeyboardListener>(); LimitedSpace.Initialize(); DataProvider.Initialize(); SteamIdHelper.Initialize(AppArguments.Get(AppFlag.ForceSteamId)); TestKey(); AppDomain.CurrentDomain.ProcessExit += OnProcessExit; if (!AppArguments.GetBool(AppFlag.PreventDisableWebBrowserEmulationMode) && ( ValuesStorage.Get <int>(WebBrowserEmulationModeDisabledKey) < WebBrowserHelper.EmulationModeDisablingVersion || AppArguments.GetBool(AppFlag.ForceDisableWebBrowserEmulationMode))) { try { WebBrowserHelper.DisableBrowserEmulationMode(); ValuesStorage.Set(WebBrowserEmulationModeDisabledKey, WebBrowserHelper.EmulationModeDisablingVersion); } catch (Exception e) { Logging.Warning("Can’t disable emulation mode: " + e); } } JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.None, NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Include, Culture = CultureInfo.InvariantCulture }; AcToolsLogging.Logger = (s, m, p, l) => Logging.Write($"{s} (AcTools)", m, p, l); AcToolsLogging.NonFatalErrorHandler = (s, c, e, b) => { if (b) { NonfatalError.NotifyBackground(s, c, e); } else { NonfatalError.Notify(s, c, e); } }; AppArguments.Set(AppFlag.ControlsDebugMode, ref ControlsSettings.OptionDebugControlles); AppArguments.Set(AppFlag.ControlsRescanPeriod, ref DirectInputScanner.OptionMinRescanPeriod); var ignoreControls = AppArguments.Get(AppFlag.IgnoreControls); if (!string.IsNullOrWhiteSpace(ignoreControls)) { ControlsSettings.OptionIgnoreControlsFilter = Filter.Create(new StringTester(), ignoreControls); } var sseStart = AppArguments.Get(AppFlag.SseName); if (!string.IsNullOrWhiteSpace(sseStart)) { SseStarter.OptionStartName = sseStart; } AppArguments.Set(AppFlag.SseLogging, ref SseStarter.OptionLogging); FancyBackgroundManager.Initialize(); if (AppArguments.Has(AppFlag.UiScale)) { AppearanceManager.Instance.AppScale = AppArguments.GetDouble(AppFlag.UiScale, 1d); } if (AppArguments.Has(AppFlag.WindowsLocationManagement)) { AppearanceManager.Instance.ManageWindowsLocation = AppArguments.GetBool(AppFlag.WindowsLocationManagement, true); } if (!InternalUtils.IsAllRight) { AppAppearanceManager.OptionCustomThemes = false; } else { AppArguments.Set(AppFlag.CustomThemes, ref AppAppearanceManager.OptionCustomThemes); } AppArguments.Set(AppFlag.FancyHintsDebugMode, ref FancyHint.OptionDebugMode); AppArguments.Set(AppFlag.FancyHintsMinimumDelay, ref FancyHint.OptionMinimumDelay); AppArguments.Set(AppFlag.WindowsVerbose, ref DpiAwareWindow.OptionVerboseMode); AppArguments.Set(AppFlag.ShowroomUiVerbose, ref LiteShowroomFormWrapperWithTools.OptionAttachedToolsVerboseMode); AppArguments.Set(AppFlag.BenchmarkReplays, ref GameDialog.OptionBenchmarkReplays); // Shared memory, now as an app flag SettingsHolder.Drive.WatchForSharedMemory = !AppArguments.GetBool(AppFlag.DisableSharedMemory); /*AppAppearanceManager.OptionIdealFormattingModeDefaultValue = AppArguments.GetBool(AppFlag.IdealFormattingMode, * !Equals(DpiAwareWindow.OptionScale, 1d));*/ NonfatalErrorSolution.IconsDictionary = new Uri("/AcManager.Controls;component/Assets/IconData.xaml", UriKind.Relative); AppearanceManager.DefaultValuesSource = new Uri("/AcManager.Controls;component/Assets/ModernUI.Default.xaml", UriKind.Relative); AppAppearanceManager.Initialize(Pages.Windows.MainWindow.GetTitleLinksEntries()); VisualExtension.RegisterInput <WebBlock>(); ContentUtils.Register("AppStrings", AppStrings.ResourceManager); ContentUtils.Register("ControlsStrings", ControlsStrings.ResourceManager); ContentUtils.Register("ToolsStrings", ToolsStrings.ResourceManager); ContentUtils.Register("UiStrings", UiStrings.ResourceManager); AcObjectsUriManager.Register(new UriProvider()); { var uiFactory = new GameWrapperUiFactory(); GameWrapper.RegisterFactory(uiFactory); ServerEntry.RegisterFactory(uiFactory); } GameWrapper.RegisterFactory(new DefaultAssistsFactory()); LapTimesManager.Instance.SetListener(); RaceResultsStorage.Instance.SetListener(); AcError.RegisterFixer(new AcErrorFixer()); AcError.RegisterSolutionsFactory(new SolutionsFactory()); InitializePresets(); SharingHelper.Initialize(); SharingUiHelper.Initialize(AppArguments.GetBool(AppFlag.ModernSharing) ? new Win10SharingUiHelper() : null); { var addonsDir = FilesStorage.Instance.GetFilename("Addons"); var pluginsDir = FilesStorage.Instance.GetFilename("Plugins"); if (Directory.Exists(addonsDir) && !Directory.Exists(pluginsDir)) { Directory.Move(addonsDir, pluginsDir); } else { pluginsDir = FilesStorage.Instance.GetDirectory("Plugins"); } PluginsManager.Initialize(pluginsDir); PluginsWrappers.Initialize( new AssemblyResolvingWrapper(KnownPlugins.Fmod, FmodResolverService.Resolver), new AssemblyResolvingWrapper(KnownPlugins.Fann, FannResolverService.Resolver), new AssemblyResolvingWrapper(KnownPlugins.Magick, ImageUtils.MagickResolver), new AssemblyResolvingWrapper(KnownPlugins.CefSharp, CefSharpResolverService.Resolver)); } { var onlineMainListFile = FilesStorage.Instance.GetFilename("Online Servers", "Main List.txt"); var onlineFavouritesFile = FilesStorage.Instance.GetFilename("Online Servers", "Favourites.txt"); if (File.Exists(onlineMainListFile) && !File.Exists(onlineFavouritesFile)) { Directory.Move(onlineMainListFile, onlineFavouritesFile); } } CupClient.Initialize(); Superintendent.Initialize(); ModsWebBrowser.Initialize(); AppArguments.Set(AppFlag.OfflineMode, ref AppKeyDialog.OptionOfflineMode); WebBlock.DefaultDownloadListener = new WebDownloadListener(); FlexibleLoader.CmRequestHandler = new CmRequestHandler(); ContextMenus.ContextMenusProvider = new ContextMenusProvider(); PrepareUi(); AppShortcut.Initialize("Content Manager", "Content Manager"); // If shortcut exists, make sure it has a proper app ID set for notifications if (File.Exists(AppShortcut.ShortcutLocation)) { AppShortcut.CreateShortcut(); } AppIconService.Initialize(new AppIconProvider()); Toast.SetDefaultAction(() => (Current.Windows.OfType <ModernWindow>().FirstOrDefault(x => x.IsActive) ?? Current.MainWindow as ModernWindow)?.BringToFront()); BbCodeBlock.ImageClicked += OnBbImageClick; BbCodeBlock.OptionEmojiProvider = new EmojiProvider(); BbCodeBlock.OptionImageCacheDirectory = FilesStorage.Instance.GetTemporaryFilename("Images"); BbCodeBlock.OptionEmojiCacheDirectory = FilesStorage.Instance.GetTemporaryFilename("Emoji"); BbCodeBlock.AddLinkCommand(new Uri("cmd://findMissing/car"), new DelegateCommand <string>( id => { WindowsHelper.ViewInBrowser(SettingsHolder.Content.MissingContentSearch.GetUri(id, SettingsHolder.MissingContentType.Car)); })); BbCodeBlock.AddLinkCommand(new Uri("cmd://findMissing/track"), new DelegateCommand <string>( id => { WindowsHelper.ViewInBrowser(SettingsHolder.Content.MissingContentSearch.GetUri(id, SettingsHolder.MissingContentType.Track)); })); BbCodeBlock.AddLinkCommand(new Uri("cmd://downloadMissing/car"), new DelegateCommand <string>(id => { var s = id.Split('|'); IndexDirectDownloader.DownloadCarAsync(s[0], s.ArrayElementAtOrDefault(1)).Forget(); })); BbCodeBlock.AddLinkCommand(new Uri("cmd://downloadMissing/track"), new DelegateCommand <string>(id => { var s = id.Split('|'); IndexDirectDownloader.DownloadTrackAsync(s[0], s.ArrayElementAtOrDefault(1)).Forget(); })); BbCodeBlock.AddLinkCommand(new Uri("cmd://createNeutralLut"), new DelegateCommand <string>(id => NeutralColorGradingLut.CreateNeutralLut(id.As(16)))); BbCodeBlock.DefaultLinkNavigator.PreviewNavigate += (sender, args) => { if (args.Uri.IsAbsoluteUri && args.Uri.Scheme == "acmanager") { ArgumentsHandler.ProcessArguments(new[] { args.Uri.ToString() }, true).Forget(); args.Cancel = true; } }; AppArguments.SetSize(AppFlag.ImagesCacheLimit, ref BetterImage.OptionCacheTotalSize); AppArguments.Set(AppFlag.ImagesMarkCached, ref BetterImage.OptionMarkCached); BetterImage.RemoteUserAgent = CmApiProvider.UserAgent; BetterImage.RemoteCacheDirectory = BbCodeBlock.OptionImageCacheDirectory; GameWrapper.Started += (sender, args) => { BetterImage.CleanUpCache(); GCHelper.CleanUp(); }; AppArguments.Set(AppFlag.UseVlcForAnimatedBackground, ref DynamicBackground.OptionUseVlc); Filter.OptionSimpleMatching = true; GameResultExtension.RegisterNameProvider(new GameSessionNameProvider()); CarBlock.CustomShowroomWrapper = new CustomShowroomWrapper(); CarBlock.CarSetupsView = new CarSetupsView(); SettingsHolder.Content.OldLayout = AppArguments.GetBool(AppFlag.CarsOldLayout); var acRootIsFine = Superintendent.Instance.IsReady && !AcRootDirectorySelector.IsReviewNeeded(); if (acRootIsFine && SteamStarter.Initialize(AcRootDirectory.Instance.Value)) { if (SettingsHolder.Drive.SelectedStarterType != SettingsHolder.DriveSettings.SteamStarterType) { SettingsHolder.Drive.SelectedStarterType = SettingsHolder.DriveSettings.SteamStarterType; Toast.Show("Starter changed to replacement", "Enjoy Steam being included into CM"); } } else if (SettingsHolder.Drive.SelectedStarterType == SettingsHolder.DriveSettings.SteamStarterType) { SettingsHolder.Drive.SelectedStarterType = SettingsHolder.DriveSettings.DefaultStarterType; Toast.Show($"Starter changed to {SettingsHolder.Drive.SelectedStarterType.DisplayName}", "Steam Starter is unavailable", () => { ModernDialog.ShowMessage( "To use Steam Starter, please make sure CM is taken place of the official launcher and AC root directory is valid.", "Steam Starter is unavailable", MessageBoxButton.OK); }); } InitializeUpdatableStuff(); BackgroundInitialization(); ExtraProgressRings.Initialize(); FatalErrorMessage.Register(new AppRestartHelper()); ImageUtils.SafeMagickWrapper = fn => { try { return(fn()); } catch (OutOfMemoryException e) { NonfatalError.Notify(ToolsStrings.MagickNet_CannotLoad, ToolsStrings.MagickNet_CannotLoad_Commentary, e); } catch (Exception e) { NonfatalError.Notify(ToolsStrings.MagickNet_CannotLoad, e); } return(null); }; DataFileBase.ErrorsCatcher = new DataSyntaxErrorCatcher(); AppArguments.Set(AppFlag.SharedMemoryLiveReadingInterval, ref AcSharedMemory.OptionLiveReadingInterval); AcSharedMemory.Initialize(); AppArguments.Set(AppFlag.RunRaceInformationWebserver, ref PlayerStatsManager.OptionRunStatsWebserver); AppArguments.Set(AppFlag.RaceInformationWebserverFile, ref PlayerStatsManager.OptionWebserverFilename); PlayerStatsManager.Instance.SetListener(); RhmService.Instance.SetListener(); WheelOptionsBase.SetStorage(new WheelAnglesStorage()); _hibernator = new AppHibernator(); _hibernator.SetListener(); VisualCppTool.Initialize(FilesStorage.Instance.GetDirectory("Plugins", "NativeLibs")); try { SetRenderersOptions(); } catch (Exception e) { VisualCppTool.OnException(e, null); } CommonFixes.Initialize(); CmPreviewsTools.MissingShowroomHelper = new CarUpdatePreviewsDialog.MissingShowroomHelper(); // Paint shop+livery generator? LiteShowroomTools.LiveryGenerator = new LiveryGenerator(); // Discord if (AppArguments.Has(AppFlag.DiscordCmd)) { // Do not show main window and wait for futher instructions? } if (SettingsHolder.Integrated.DiscordIntegration) { AppArguments.Set(AppFlag.DiscordVerbose, ref DiscordConnector.OptionVerboseMode); DiscordConnector.Initialize(AppArguments.Get(AppFlag.DiscordClientId) ?? InternalUtils.GetDiscordClientId(), new DiscordHandler()); DiscordImage.OptionDefaultImage = @"track_ks_brands_hatch"; GameWrapper.Started += (sender, args) => args.StartProperties.SetAdditional(new GameDiscordPresence(args.StartProperties, args.Mode)); } // Reshade? var loadReShade = AppArguments.GetBool(AppFlag.ForceReshade); if (!loadReShade && string.Equals(AppArguments.Get(AppFlag.ForceReshade), "kn5only", StringComparison.OrdinalIgnoreCase)) { loadReShade = AppArguments.Values.Any(x => x.EndsWith(".kn5", StringComparison.OrdinalIgnoreCase)); } if (loadReShade) { var reshade = Path.Combine(MainExecutingFile.Directory, "dxgi.dll"); if (File.Exists(reshade)) { Kernel32.LoadLibrary(reshade); } } // Auto-show that thing InstallAdditionalContentDialog.Initialize(); // Let’s roll ShutdownMode = ShutdownMode.OnExplicitShutdown; new AppUi(this).Run(); }
private Prompt(string title, string description, string defaultValue, string placeholder, string toolTip, bool multiline, bool passwordMode, bool required, int maxLength, IEnumerable <string> suggestions, bool suggestionsFixed, string comment) { DataContext = new ViewModel(description, defaultValue, placeholder, toolTip, required); InitializeComponent(); Buttons = new[] { OkButton, CancelButton }; _multiline = multiline; if (required) { OkButton.SetBinding(IsEnabledProperty, new Binding { Source = DataContext, Path = new PropertyPath(nameof(ViewModel.Text)), Converter = this }); } if (comment != null) { ButtonsRowContent = new BbCodeBlock { Text = comment, Style = (Style)FindResource(@"BbCodeBlock.Small") }; ButtonsRowContentAlignment = HorizontalAlignment.Left; } Title = title; FrameworkElement element; if (passwordMode) { var passwordBox = new ProperPasswordBox(); passwordBox.SetBinding(ProperPasswordBox.PasswordProperty, new Binding { Source = DataContext, Path = new PropertyPath(nameof(ViewModel.Text)), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged }); passwordBox.Focus(); passwordBox.SelectAll(); element = passwordBox; } else if (suggestions != null) { var comboBox = new BetterComboBox { IsEditable = !suggestionsFixed, IsTextSearchEnabled = true }; if (suggestions is INotifyCollectionChanged) { comboBox.SetBinding(ItemsControl.ItemsSourceProperty, new Binding { Source = suggestions }); } else { comboBox.ItemsSource = suggestions.ToList(); } comboBox.SetBinding(ComboBox.TextProperty, new Binding { Source = DataContext, Path = new PropertyPath(nameof(ViewModel.Text)), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, ValidatesOnDataErrors = true }); if (comboBox.Template?.FindName(@"PART_EditableTextBox", comboBox) is TextBox textBox) { textBox.SelectAll(); textBox.Focus(); } else { comboBox.Focus(); } if (placeholder != null) { comboBox.Placeholder = placeholder; } element = comboBox; } else { var textBox = new BetterTextBox(); textBox.SetBinding(TextBox.TextProperty, new Binding { Source = DataContext, Path = new PropertyPath(nameof(ViewModel.Text)), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, ValidatesOnDataErrors = true }); if (maxLength != -1) { textBox.MaxLength = maxLength; } if (multiline) { textBox.AcceptsReturn = true; textBox.TextWrapping = TextWrapping.Wrap; textBox.Height = 240; } if (placeholder != null) { textBox.Placeholder = placeholder; } textBox.Focus(); textBox.SelectAll(); element = textBox; } Panel.Children.Add(element); if (toolTip != null) { element.SetValue(ToolTipProperty, toolTip); } PreviewKeyDown += OnKeyDown; element.PreviewKeyDown += OnKeyDown; Closing += (sender, args) => { if (MessageBoxResult != MessageBoxResult.OK) { return; } Result = Model.Text; }; }
protected MaterialValueBase(string name) { Id = name; _name = BbCodeBlock.Encode(name); }
protected override void OnMouseMove(MouseEventArgs e) { if (_scrolling) { return; } var size = _size; var width = size.Width; var pos = this.GetMousePosition(); var referenceIconOffset = 22d; for (var i = 0; i < _icons.Length; i++) { var icon = _icons[i]; if (icon == null) { break; } var iconWidth = icon.Width; var rect = new Rect(referenceIconOffset, 5, iconWidth, ReferenceIconSize); if (rect.Contains(pos)) { ShowToolTip($@"ref:{i}", () => _iconToolTips.ArrayElementAtOrDefault(i)); return; } referenceIconOffset += iconWidth + ReferenceIconMargin; } if (!_fullyLoaded) { return; } var pieces = (_bookedForPlayer ? 1 : 0) + (_passwordRequired ? 1 : 0) + (_hasFriends ? 1 : 0); var iconOffset = (60d - pieces * ReferenceIconHeight + (pieces - 1d) * ReferenceIconMargin) / 2d; if (pieces > 0) { const double iconHeight = 12d; const double iconMargin = 4d; if (_bookedForPlayer) { if (new Rect(6, iconOffset, 12, iconHeight).Contains(pos)) { ShowToolTip(@"iconBooked", () => "There is a place booked for you"); return; } iconOffset += iconHeight + iconMargin; } if (_passwordRequired) { if (new Rect(6, iconOffset, 12, iconHeight).Contains(pos)) { ShowToolTip(@"iconPassword", () => ControlsStrings.Online_PasswordRequired); return; } iconOffset += iconHeight + iconMargin; } if (_hasFriends) { if (new Rect(6, iconOffset, 12, iconHeight).Contains(pos)) { ShowToolTip(@"iconFriends", () => "Your friend is here"); return; } // iconOffset += iconHeight + iconMargin; } } if (new Rect(width - 80, 0, 40, 30).Contains(pos)) { ShowToolTip(@"clients", () => FindStaticResource <ToolTip>(@"ClientsTooltip")); return; } if (new Rect(width - 40, 0, 40, 30).Contains(pos)) { if (_errorFlag) { ShowToolTip(@"error", () => _server.ErrorsString?.Trim()); } else { ShowToolTip(@"ping", () => $"Ping: {(_server.Ping.HasValue ? _server.Ping + " ms" : "not checked yet")}"); } return; } if (GetCountryRect(width).Contains(pos)) { ShowToolTip(@"country", () => _server.Country); return; } #if DEBUG if (new Rect(0, 0, width, 30).Contains(pos)) { ShowToolTip(@"name", () => $"Actual name: {BbCodeBlock.Encode(_server.ActualName)}\nSorting name: {_server.SortingName}"); return; } #endif if (GetTrackRect().Contains(pos)) { ShowToolTip(@"track", () => FindStaticResource <ToolTip>(@"TrackPreviewTooltip.Online")); return; } if (new Rect(146d, 35, _sessionsCount * 20 + (_wideMode ? 84d : 0), 20).Contains(pos)) { ShowToolTip(@"sessions", () => FindStaticResource <ToolTip>(@"SessionsItemTooltip")); return; } var carsOffset = _wideMode ? 324d : 240d; if (GetCarsRect(carsOffset, width).Contains(pos)) { var cars = _cars; for (var i = 0; i < cars.Length; i++) { var c = cars[i]; if (c == null || carsOffset > width) { break; } var rect = new Rect(carsOffset, 34, c.Width + 8, 22); if (rect.Contains(pos)) { ShowToolTip($@"car:{i}", () => FindStaticResource <ToolTip>(@"CarPreviewTooltip.Online"), () => _server.Cars?.ElementAtOrDefault(i)); return; } carsOffset += rect.Width + 8; } } ShowToolTip(null, null); }
private void InnerWrite(string message, string color = null, int level = 0, bool extraHalf = false) { _destination.Add($@"{@" ".RepeatString(level * 2 + (extraHalf ? 1 : 0))}{ (color != null ? $@"[color=#{color}]" : "")}{BbCodeBlock.Encode(message)}{(color != null ? @"[/color]" : "")}"); }