public void Initialise(ServerEntry serverEntry) { if (serverEntry != null) { textBoxServerName.Text = serverEntry.ServerName; textBoxServerType.Text = serverEntry.ServerType.ToString(); textBoxServerCLSID.Text = serverEntry.ClassId.ToString(); textBoxServerSecurity.Text = serverEntry.GetSecurityStatus(); textBoxAssemblyPath.Text = serverEntry.ServerPath; // Get the specified associations. var associationType = COMServerAssociationAttribute.GetAssociationType(serverEntry.Server.GetType()); var associations = COMServerAssociationAttribute.GetAssociations(serverEntry.Server.GetType()); textBoxAssociations.Text = associationType.ToString() + " " + string.Join(", ", associations); // Now use the server registration manager to get the registration info // for the different operating system architectures. var info32 = ServerRegistrationManager.GetServerRegistrationInfo(serverEntry.Server.ServerClsid, RegistrationType.OS32Bit); var info64 = ServerRegistrationManager.GetServerRegistrationInfo(serverEntry.Server.ServerClsid, RegistrationType.OS64Bit); // By default, our installation info is going to be empty. textBox32BitServer.Text = "Not Installed"; textBox64BitServer.Text = "Not Installed"; // Do we have 32 bit registration info? if (info32 != null) { // Do we have a codebase? if (!string.IsNullOrEmpty(info32.CodeBase)) textBox32BitServer.Text = info32.CodeBase; else if (!string.IsNullOrEmpty(info32.Assembly)) textBox32BitServer.Text = info32.Assembly + " (GAC)"; } // Do we have 32 bit registration info? if (info64 != null) { // Do we have a codebase? if (!string.IsNullOrEmpty(info64.CodeBase)) textBox64BitServer.Text = info64.CodeBase; else if (!string.IsNullOrEmpty(info64.Assembly)) textBox64BitServer.Text = info64.Assembly + " (GAC)"; } } }
public override int Compare(ServerEntry x, ServerEntry y) { var dif = -(x.Cars?.Count ?? 0).CompareTo(y.Cars?.Count ?? 0); return(dif == 0 ? string.Compare(x.SortingName, y.SortingName, StringComparison.Ordinal) : dif); }
private async Task WaitForCancellationAsync() { while (!_cts.IsCancellationRequested) { if (!Ready) { await Task.Delay(TimeSpan.FromMilliseconds(500)); continue; } lock (_lockerObject) { Task.Run(async() => { while (Ready) { if (DateTime.Now >= _nextStatusCheck) { _nextStatusCheck = DateTime.Now + Program.Config.UpdateDelay; try { var request = (HttpWebRequest)WebRequest.Create(Program.Config.StatusURL); request.ContentType = "application/json"; request.Credentials = CredentialCache.DefaultCredentials; var res = request.GetResponse(); var serverList = new List <ServerModel>(); await using (var stream = res.GetResponseStream()) { if (stream != null) { using var reader = new StreamReader(stream); var result = await reader.ReadToEndAsync(); serverList = JsonConvert.DeserializeObject <List <ServerModel> >(result); } } res.Close(); res.Dispose(); foreach (var serverModel in serverList) { if (await Program.ServerStatusRepository.EntryExists(Convert.ToInt32(serverModel.Id))) { var model = await Program.ServerStatusRepository.FindById( Convert.ToInt32(serverModel.Id)); model.CurrentStatus.EditTime = DateTime.Now; model.CurrentStatus.Online = serverModel.Online == "1"; model.CurrentStatus.UserCount = Convert.ToInt32(serverModel.UserCount); model.History = new List <ServerEntryStatusHistory> { new ServerEntryStatusHistory { EntryTime = DateTime.Now, Id = Guid.NewGuid(), Online = serverModel.Online == "1", ServerId = model.Id, UserCount = model.CurrentStatus.UserCount } }; await Program.ServerStatusRepository.UpdateCurrentStatusAsync(model); } else { var model = new ServerEntry { CurrentStatus = new ServerEntryStatus(), ExpRate = serverModel.EXPRate, Id = Guid.NewGuid(), RgbColor = "rgb(0, 0, 0)", ServerId = Convert.ToInt32(serverModel.Id), ServerName = serverModel.Name, ServerType = serverModel.Type }; model.CurrentStatus.Id = Guid.NewGuid(); model.CurrentStatus.EditTime = DateTime.Now; model.CurrentStatus.Online = serverModel.Online == "1"; model.CurrentStatus.UserCount = Convert.ToInt32(serverModel.UserCount); model.History = new List <ServerEntryStatusHistory> { new ServerEntryStatusHistory { EntryTime = DateTime.Now, Id = Guid.NewGuid(), Online = serverModel.Online == "1", ServerId = model.Id, UserCount = model.CurrentStatus.UserCount } }; await _serverStatusRepository.AddServerAsync(model); } } } catch (Exception e) { Program.Log(e); } } if (DateTime.Now < _nextOutputTime) { await Task.Delay(500); continue; } _nextOutputTime = DateTime.Now + Program.Config.OutputDelay; try { var models = await _serverStatusRepository.GetAllAsync(); models = models.OrderByDescending(a => a.CurrentStatus.Online) .ThenByDescending(a => a.CurrentStatus.UserCount != -1) .ThenByDescending(a => a.CurrentStatus.UserCount).ToList(); var temp = "```md\r\n"; foreach (var serverEntry in models) { temp += Program.Config.OutputFormat .Replace("$SERVERNAME$", serverEntry.ServerName) .Replace("$STATUS$", serverEntry.CurrentStatus.Online ? "Online" : "Offline") .Replace("$USERCOUNT$", $"{serverEntry.CurrentStatus.UserCount}"); if (!temp.EndsWith("\r\n")) { temp += "\r\n"; } } temp += "```"; if (_lastMessage != null) { await _channel.DeleteMessageAsync(_lastMessage); } else { var currentMessages = await _channel.GetMessagesAsync(); if (currentMessages != null) { await _channel.DeleteMessagesAsync(currentMessages); } } _lastMessage = await _channel.SendMessageAsync(temp); } catch (Exception e) { Program.Log(e); } await Task.Delay(500); } }); } await Task.Delay(-1); } }
private void SaveData() { for (int i = 0; i < serverList.Items.Count; i++) { for (int j = i + 1; j < serverList.Items.Count; j++) { ServerEntry si = (ServerEntry)serverList.Items[i]; ServerEntry sj = (ServerEntry)serverList.Items[j]; if (si.Address == sj.Address && si.Port == sj.Port) { serverList.Items.RemoveAt(j); } } } int num = 1; for (int i = 0; i < serverList.Items.Count; i++) { ServerEntry se = (ServerEntry)serverList.Items[i]; if (se is Custom_SE || se is LoginCFG_SE) { continue; } if (se.Address != "") { Config.SetRegString(Microsoft.Win32.Registry.CurrentUser, String.Format("Server{0}", num), se.Address); Config.SetRegString(Microsoft.Win32.Registry.CurrentUser, String.Format("Port{0}", num), se.Port.ToString()); num++; } } for (int i = 2; i < clientList.Items.Count; i++) { Config.SetRegString(Microsoft.Win32.Registry.CurrentUser, String.Format("Client{0}", i - 1), ((PathElipsis)clientList.Items[i]).GetPath()); } num = 1; if (dataDir.SelectedIndex == -1) { string dir = dataDir.Text; dir = dir.Trim(); if (dir.Length > 0 && dir != "(Auto Detect)") { Config.SetRegString(Microsoft.Win32.Registry.CurrentUser, "Dir1", dir); Config.SetRegString(Microsoft.Win32.Registry.CurrentUser, "LastDir", "1"); m_DataDir = dir; num = 2; } } if (num == 1) { Config.SetRegString(Microsoft.Win32.Registry.CurrentUser, "LastDir", (dataDir.SelectedIndex != -1 ? dataDir.SelectedIndex : 0).ToString()); try { if (dataDir.SelectedIndex != 0) { m_DataDir = dataDir.SelectedItem as string; } else { m_DataDir = null; } } catch { } } for (int i = 1; i < dataDir.Items.Count; i++) { Config.SetRegString(Microsoft.Win32.Registry.CurrentUser, String.Format("Dir{0}", num++), (string)dataDir.Items[i]); } }
private void WelcomeForm_Load(object sender, System.EventArgs e) { Language.LoadControlNames(this); this.BringToFront(); langSel.Items.AddRange(Language.GetPackNames()); langSel.SelectedItem = Language.Current; showAtStart.Checked = Utility.ToInt32(Config.GetRegString(Microsoft.Win32.Registry.CurrentUser, "ShowWindow"), 1) == 1; clientList.Items.Add(Language.GetString(LocString.Auto2D)); clientList.Items.Add(Language.GetString(LocString.Auto3D)); for (int i = 1; ; i++) { string val = String.Format("Client{0}", i); string cli = Config.GetRegString(Microsoft.Win32.Registry.CurrentUser, val); if (cli == null || cli == "") { break; } if (File.Exists(cli)) { clientList.Items.Add(new PathElipsis(cli)); } Config.DeleteRegValue(Microsoft.Win32.Registry.CurrentUser, val); } int sel = Utility.ToInt32(Config.GetRegString(Microsoft.Win32.Registry.CurrentUser, "DefClient"), 0); if (sel >= clientList.Items.Count) { sel = 0; Config.SetRegString(Microsoft.Win32.Registry.CurrentUser, "DefClient", "0"); } clientList.SelectedIndex = sel; dataDir.Items.Add(Language.GetString(LocString.AutoDetect)); for (int i = 1; ; i++) { string val = String.Format("Dir{0}", i); string dir = Config.GetRegString(Microsoft.Win32.Registry.CurrentUser, val); if (dir == null || dir == "") { break; } if (Directory.Exists(dir)) { dataDir.Items.Add(dir); } Config.DeleteRegValue(Microsoft.Win32.Registry.CurrentUser, val); } try { dataDir.SelectedIndex = Convert.ToInt32(Config.GetRegString(Microsoft.Win32.Registry.CurrentUser, "LastDir")); } catch { dataDir.SelectedIndex = 0; } patchEncy.Checked = Utility.ToInt32(Config.GetRegString(Microsoft.Win32.Registry.CurrentUser, "PatchEncy"), 1) != 0; useEnc.Checked = Utility.ToInt32(Config.GetRegString(Microsoft.Win32.Registry.CurrentUser, "ServerEnc"), 0) != 0; LoginCFG_SE lse = new LoginCFG_SE(); Custom_SE cse; ShardEntry[] entries = null; try { entries = JsonConvert.DeserializeObject <ShardEntry[]>(Engine.ShardList); } catch { } serverList.BeginUpdate(); //serverList.Items.Add( lse=new LoginCFG_SE() ); //serverList.SelectedItem = lse; for (int i = 1; ; i++) { ServerEntry se; string sval = String.Format("Server{0}", i); string serv = Config.GetRegString(Microsoft.Win32.Registry.CurrentUser, sval); if (serv == null) { break; } string pval = String.Format("Port{0}", i); int port = Utility.ToInt32(Config.GetRegString(Microsoft.Win32.Registry.CurrentUser, pval), 0); serverList.Items.Add(se = new ServerEntry(serv, port)); if (serv == lse.RealAddress && port == lse.Port) { serverList.SelectedItem = se; } Config.DeleteRegValue(Microsoft.Win32.Registry.CurrentUser, sval); Config.DeleteRegValue(Microsoft.Win32.Registry.CurrentUser, pval); } if (entries == null) { serverList.Items.Add(cse = new Custom_SE("Zenvera (UOR)", "login.zenvera.com")); if (serverList.SelectedItem == null || lse.RealAddress == cse.RealAddress && lse.Port == 2593) { serverList.SelectedItem = cse; } } else { foreach (var entry in entries) { if (String.IsNullOrEmpty(entry.name)) { continue; } var ename = String.IsNullOrEmpty(entry.type) ? entry.name : String.Format("{0} ({1})", entry.name, entry.type); serverList.Items.Add(cse = new Custom_SE(ename, entry.host, entry.port)); if (lse.RealAddress == cse.RealAddress && lse.Port == entry.port) { serverList.SelectedItem = cse; } } } serverList.EndUpdate(); serverList.Refresh(); WindowState = FormWindowState.Normal; this.BringToFront(); this.TopMost = true; _ShowTimer = new System.Windows.Forms.Timer(); _ShowTimer.Interval = 250; _ShowTimer.Enabled = true; _ShowTimer.Tick += new EventHandler(timer_Tick); }
public async Task AddServerAsync(ServerEntry serverEntry) { await AddStat(serverEntry); await _db.GetCollection <ServerEntry>(ServersTable).InsertOneAsync(serverEntry); }
public void Add(ServerEntry entry) { this.entries.Add(entry); }
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 void UpdateErrorFlag(ServerEntry n) { _hasErrorsGroup.Value = n.HasErrors || !n.IsFullyLoaded; }
private void UpdateCars(ServerEntry n) { var array = n.Cars; var children = _carsPanel.Children; var carsCount = Math.Min(array?.Count ?? 0, OptionCarsLimit); for (var i = children.Count - carsCount; i > 0; i--) { var last = children.Count - 1; var child = (TextBlockBindable)children[last]; DisposeHelper.Dispose(ref child.Bind); if (CarsPool.Count < CarsPoolSize) { CarsPool.Add(child); } children.RemoveAt(last); } if (array == null) { return; } for (var i = 0; i < carsCount; i++) { TextBlockBindable child; if (i < children.Count) { child = (TextBlockBindable)children[i]; } else { if (CarsPool.Count > 0) { var last = CarsPool.Count - 1; child = CarsPool[last]; CarsPool.RemoveAt(last); } else { if (_smallStyle == null) { _smallStyle = (Style)FindResource(@"Small"); } child = new TextBlockBindable { Style = _smallStyle, Margin = new Thickness(4, 0, 4, 0), Padding = new Thickness(2), Height = 20d, Foreground = _blockText, Background = _blockBackground }; } children.Add(child); } UpdateCar(child, array[i]); } }
private void WelcomeForm_Load(object sender, System.EventArgs e) { Language.LoadControlNames(this); this.BringToFront(); langSel.Items.AddRange(Language.GetPackNames()); langSel.SelectedItem = Language.Current; showAtStart.Checked = Utility.ToInt32(Config.GetRegString(Microsoft.Win32.Registry.CurrentUser, "ShowWindow"), 1) == 1; clientList.Items.Add(Language.GetString(LocString.Auto2D)); clientList.Items.Add(Language.GetString(LocString.Auto3D)); for (int i = 1; ; i++) { string val = String.Format("Client{0}", i); string cli = Config.GetRegString(Microsoft.Win32.Registry.CurrentUser, val); if (cli == null || cli == "") { break; } if (File.Exists(cli)) { clientList.Items.Add(new PathElipsis(cli)); } Config.DeleteRegValue(Microsoft.Win32.Registry.CurrentUser, val); } int sel = Utility.ToInt32(Config.GetRegString(Microsoft.Win32.Registry.CurrentUser, "DefClient"), 0); if (sel >= clientList.Items.Count) { sel = 0; Config.SetRegString(Microsoft.Win32.Registry.CurrentUser, "DefClient", "0"); } clientList.SelectedIndex = sel; dataDir.Items.Add(Language.GetString(LocString.AutoDetect)); for (int i = 1; ; i++) { string val = String.Format("Dir{0}", i); string dir = Config.GetRegString(Microsoft.Win32.Registry.CurrentUser, val); if (dir == null || dir == "") { break; } if (Directory.Exists(dir)) { dataDir.Items.Add(dir); } Config.DeleteRegValue(Microsoft.Win32.Registry.CurrentUser, val); } try { dataDir.SelectedIndex = Convert.ToInt32(Config.GetRegString(Microsoft.Win32.Registry.CurrentUser, "LastDir")); } catch { dataDir.SelectedIndex = 0; } patchEncy.Checked = Utility.ToInt32(Config.GetRegString(Microsoft.Win32.Registry.CurrentUser, "PatchEncy"), 1) != 0; useEnc.Checked = Utility.ToInt32(Config.GetRegString(Microsoft.Win32.Registry.CurrentUser, "ServerEnc"), 0) != 0; LoginCFG_SE lse = new LoginCFG_SE(); UOGamers_SE uog; serverList.BeginUpdate(); //serverList.Items.Add( lse=new LoginCFG_SE() ); //serverList.SelectedItem = lse; for (int i = 1; ; i++) { ServerEntry se; string sval = String.Format("Server{0}", i); string serv = Config.GetRegString(Microsoft.Win32.Registry.CurrentUser, sval); if (serv == null) { break; } string pval = String.Format("Port{0}", i); int port = Utility.ToInt32(Config.GetRegString(Microsoft.Win32.Registry.CurrentUser, pval), 0); serverList.Items.Add(se = new ServerEntry(serv, port)); if (serv == lse.RealAddress && port == lse.Port) { serverList.SelectedItem = se; } Config.DeleteRegValue(Microsoft.Win32.Registry.CurrentUser, sval); Config.DeleteRegValue(Microsoft.Win32.Registry.CurrentUser, pval); } serverList.Items.Add(uog = new UOGamers_SE("Zenvera (UOR)", "login.zenvera.com")); if (serverList.SelectedItem == null || lse.RealAddress == uog.RealAddress && lse.Port == 2593) { serverList.SelectedItem = uog; } serverList.Items.Add(uog = new UOGamers_SE("Second Age (T2A)", "login.uosecondage.com")); if (lse.RealAddress == uog.RealAddress && lse.Port == 2593) { serverList.SelectedItem = uog; } serverList.Items.Add(uog = new UOGamers_SE("An Corp (T2A)", "login.uoancorp.com")); if (lse.RealAddress == uog.RealAddress && lse.Port == 2593) { serverList.SelectedItem = uog; } serverList.Items.Add(uog = new UOGamers_SE("Forever (P16)", "login.uoforever.com", 2599)); if (lse.RealAddress == uog.RealAddress && lse.Port == 2599) { serverList.SelectedItem = uog; } serverList.Items.Add(uog = new UOGamers_SE("Pandora (HS)", "play.pandorauo.com")); if (lse.RealAddress == uog.RealAddress && lse.Port == 2593) { serverList.SelectedItem = uog; } serverList.Items.Add(uog = new UOGamers_SE("Electronic Arts/Origin Servers", "login.ultimaonline.com", 7775)); if (lse.RealAddress == uog.RealAddress && (lse.Port >= 7775 && lse.Port <= 7778)) { serverList.SelectedItem = uog; } serverList.EndUpdate(); serverList.Refresh(); WindowState = FormWindowState.Normal; this.BringToFront(); this.TopMost = true; _ShowTimer = new System.Windows.Forms.Timer(); _ShowTimer.Interval = 250; _ShowTimer.Enabled = true; _ShowTimer.Tick += new EventHandler(timer_Tick); }
public ServerEntryResult(ServerEntry entry) { ServerName = entry.ServerName; RgbColour = entry.RgbColor; }
public static void DeleteServer(ServerEntry entry) { ClientData.Delete(entry); }
public static void SaveServer(ServerEntry entry) { ClientData.SaveOrUpdate(entry); }
public ControllerManager(ServerEntry server) { this.server = server; InitController(); }
public override int Compare(ServerEntry x, ServerEntry y) { return(string.Compare(x.SortingName, y.SortingName, StringComparison.CurrentCultureIgnoreCase)); }
private void okay_Click(object sender, System.EventArgs e) { m_PatchEncy = patchEncy.Checked; if ( clientList.SelectedIndex < 2 ) { m_Launch = (ClientLaunch)clientList.SelectedIndex; } else { m_Launch = ClientLaunch.Custom; m_ClientPath = ((PathElipsis)clientList.SelectedItem).GetPath(); } ServerEntry se = null; if ( serverList.SelectedItem != null ) { if ( serverList.SelectedItem is UOGamers_SE ) { int port = ((UOGamers_SE)serverList.SelectedItem).Port; string addr = ((UOGamers_SE)serverList.SelectedItem).RealAddress; if ( addr == "login.ultimaonline.com" ) { ClientCommunication.ServerEncrypted = true; } if (port == 0) port = 2593; // runuo default se = new ServerEntry( addr, port ); } else if ( !(serverList.SelectedItem is LoginCFG_SE) ) { se = (ServerEntry)serverList.SelectedItem; se.Port = Utility.ToInt32( port.Text.Trim(), 0 ); if ( se.Port <= 0 || se.Port > 65535 ) { MessageBox.Show( this, Language.GetString( LocString.NeedPort ), "Need Port", MessageBoxButtons.OK, MessageBoxIcon.Information ); return; } } } else if ( serverList.Text != "" ) { int thePort = Utility.ToInt32( port.Text.Trim(), 0 ); if ( thePort <= 0 || thePort > 65535 ) { MessageBox.Show( this, Language.GetString( LocString.NeedPort ), "Need Port", MessageBoxButtons.OK, MessageBoxIcon.Information ); return; } se = new ServerEntry( serverList.Text.Trim(), thePort ); } if ( se != null && se.Address != null ) { if ( !( serverList.SelectedItem is UOGamers_SE ) ) { serverList.Items.Remove( se ); serverList.Items.Insert( 1, se ); } //if ( se.Address != "" ) // WriteLoginCFG( se.Address, se.Port ); Config.SetRegString( Registry.CurrentUser, "LastServer", se.Address ); Config.SetRegString( Registry.CurrentUser, "LastPort", se.Port.ToString() ); } SaveData(); this.Close(); }
public void OnSelectedItemChanged(ServerEntry caller) { NotifyPropertyChanged("SelectedServerIndex"); NotifyPropertyChanged("SelectedServer"); }
private void DeleteServerEntry(ServerEntry serverEntry) { ServerEntries.Remove(serverEntry); }
public void Deserialize(string source) { IList<ServerEntry> servers = null; int selectedIndex = 0; if (source != null && source != "") { string[] parts = source.Split(';'); if (parts.Length % 3 == 1) { servers = new List<ServerEntry>(); selectedIndex = Utils.StringToInt(parts[0], -1); bool success = selectedIndex != -1; for (int i = 1; i < parts.Length && success; i += 3) { ServerEntry server = new ServerEntry(this, parts[i], Utils.StringToInt(parts[i + 1], -1), parts[i + 2]); success = server.Port != -1; servers.Add(server); } if (!success) { servers = null; } } } if (servers == null) { servers = new ServerEntry[] { new ServerEntry(this, "localhost", 6600, "", 0, false) }; } SetItems(servers, selectedIndex); }
private void OnTick(object sender, EventArgs e) { ServerEntry?.OnTick(); Ready = ServerEntry?.BookingTimeLeft == TimeSpan.Zero && ServerEntry.BookingErrorMessage == null; }
private void WelcomeForm_Load(object sender, System.EventArgs e) { Language.LoadControlNames( this ); this.BringToFront(); langSel.Items.AddRange( Language.GetPackNames() ); langSel.SelectedItem = Language.Current; showAtStart.Checked = Utility.ToInt32( Config.GetRegString( Microsoft.Win32.Registry.CurrentUser, "ShowWindow" ), 1 ) == 1; clientList.Items.Add( Language.GetString( LocString.Auto2D ) ); clientList.Items.Add( Language.GetString( LocString.Auto3D ) ); for (int i=1; ;i++) { string val = String.Format( "Client{0}", i ); string cli = Config.GetRegString( Microsoft.Win32.Registry.CurrentUser, val ); if ( cli == null || cli == "" ) break; if ( File.Exists( cli ) ) clientList.Items.Add( new PathElipsis( cli ) ); Config.DeleteRegValue( Microsoft.Win32.Registry.CurrentUser, val ); } int sel = Utility.ToInt32( Config.GetRegString( Microsoft.Win32.Registry.CurrentUser, "DefClient" ), 0 ); if ( sel >= clientList.Items.Count ) { sel = 0; Config.SetRegString( Microsoft.Win32.Registry.CurrentUser, "DefClient", "0" ); } clientList.SelectedIndex = sel; dataDir.Items.Add( Language.GetString( LocString.AutoDetect ) ); for ( int i=1; ;i++) { string val = String.Format( "Dir{0}", i ); string dir = Config.GetRegString( Microsoft.Win32.Registry.CurrentUser, val ); if ( dir == null || dir == "" ) break; if ( Directory.Exists( dir ) ) dataDir.Items.Add( dir ); Config.DeleteRegValue( Microsoft.Win32.Registry.CurrentUser, val ); } try { dataDir.SelectedIndex = Convert.ToInt32( Config.GetRegString( Microsoft.Win32.Registry.CurrentUser, "LastDir" ) ); } catch { dataDir.SelectedIndex = 0; } patchEncy.Checked = Utility.ToInt32( Config.GetRegString( Microsoft.Win32.Registry.CurrentUser, "PatchEncy" ), 1 ) != 0; useEnc.Checked = Utility.ToInt32( Config.GetRegString( Microsoft.Win32.Registry.CurrentUser, "ServerEnc" ), 0 ) != 0; LoginCFG_SE lse = new LoginCFG_SE(); Custom_SE cse; ShardEntry[] entries = null; try { entries = JsonConvert.DeserializeObject<ShardEntry[]>(Engine.ShardList); } catch { } serverList.BeginUpdate(); //serverList.Items.Add( lse=new LoginCFG_SE() ); //serverList.SelectedItem = lse; for (int i=1; ;i++) { ServerEntry se; string sval = String.Format( "Server{0}", i ); string serv = Config.GetRegString( Microsoft.Win32.Registry.CurrentUser, sval ); if ( serv == null ) break; string pval = String.Format( "Port{0}", i ); int port = Utility.ToInt32( Config.GetRegString( Microsoft.Win32.Registry.CurrentUser, pval ), 0 ); serverList.Items.Add( se=new ServerEntry( serv, port ) ); if ( serv == lse.RealAddress && port == lse.Port ) serverList.SelectedItem = se; Config.DeleteRegValue( Microsoft.Win32.Registry.CurrentUser, sval ); Config.DeleteRegValue( Microsoft.Win32.Registry.CurrentUser, pval ); } if (entries == null) { serverList.Items.Add(cse = new Custom_SE("Zenvera (UOR)", "login.zenvera.com")); if (serverList.SelectedItem == null || lse.RealAddress == cse.RealAddress && lse.Port == 2593) serverList.SelectedItem = cse; } else { foreach(var entry in entries) { if (String.IsNullOrEmpty(entry.name)) continue; var ename = String.IsNullOrEmpty(entry.type) ? entry.name : String.Format("{0} ({1})", entry.name, entry.type); serverList.Items.Add(cse = new Custom_SE(ename, entry.host, entry.port)); if (lse.RealAddress == cse.RealAddress && lse.Port == entry.port) serverList.SelectedItem = cse; } } serverList.EndUpdate(); serverList.Refresh(); WindowState = FormWindowState.Normal; this.BringToFront(); this.TopMost = true; _ShowTimer = new System.Windows.Forms.Timer(); _ShowTimer.Interval = 250; _ShowTimer.Enabled = true; _ShowTimer.Tick += new EventHandler(timer_Tick); }
public void Initialise(ServerEntry serverEntry) { if (serverEntry != null) { textBoxServerName.Text = serverEntry.ServerName; textBoxServerType.Text = serverEntry.ServerType.ToString(); textBoxServerCLSID.Text = serverEntry.ClassId.ToString(); textBoxServerSecurity.Text = serverEntry.GetSecurityStatus(); textBoxAssemblyPath.Text = serverEntry.ServerPath; if (serverEntry.IsInvalid) { // Clear other data for invalid servers. textBoxAssociations.Text = string.Empty; textBox32BitServer.Text = string.Empty; textBox64BitServer.Text = string.Empty; } else { // Get the specified associations. var associationType = COMServerAssociationAttribute.GetAssociationType(serverEntry.Server.GetType()); var associations = COMServerAssociationAttribute.GetAssociations(serverEntry.Server.GetType()); textBoxAssociations.Text = associationType.ToString() + " " + string.Join(", ", associations); // Now use the server registration manager to get the registration info // for the different operating system architectures. var info32 = ServerRegistrationManager.GetServerRegistrationInfo(serverEntry.Server.ServerClsid, RegistrationType.OS32Bit, RegistrationLocation.LocalMachine); var info64 = ServerRegistrationManager.GetServerRegistrationInfo(serverEntry.Server.ServerClsid, RegistrationType.OS64Bit, RegistrationLocation.LocalMachine); // By default, our installation info is going to be empty. textBox32BitServer.Text = "Not Installed"; textBox64BitServer.Text = "Not Installed"; textBox32BitServerRegistration.Text = "Not Registered"; textBox64BitServerRegistration.Text = "Not Registered"; // Do we have 32 bit registration info? if (info32 != null) { // Do we have a codebase? if (!string.IsNullOrEmpty(info32.CodeBase)) { textBox32BitServer.Text = info32.CodeBase; } else if (!string.IsNullOrEmpty(info32.Assembly)) { textBox32BitServer.Text = info32.Assembly + " (GAC)"; } // Set the registration info. if (info32.IsApproved) { textBox32BitServerRegistration.Text = "Registered"; } } // Do we have 32 bit registration info? if (info64 != null) { // Do we have a codebase? if (!string.IsNullOrEmpty(info64.CodeBase)) { textBox64BitServer.Text = info64.CodeBase; } else if (!string.IsNullOrEmpty(info64.Assembly)) { textBox64BitServer.Text = info64.Assembly + " (GAC)"; } // Set the registration info. if (info64.IsApproved) { textBox64BitServerRegistration.Text = "Registered"; } } } } }
public void ChangeEntry([NotNull] ServerEntry entry) { Entry = entry; }
private void okay_Click(object sender, System.EventArgs e) { m_PatchEncy = patchEncy.Checked; if (clientList.SelectedIndex < 2) { m_Launch = (ClientLaunch)clientList.SelectedIndex; } else { m_Launch = ClientLaunch.Custom; m_ClientPath = ((PathElipsis)clientList.SelectedItem).GetPath(); } ServerEntry se = null; if (serverList.SelectedItem != null) { if (serverList.SelectedItem is Custom_SE) { int port = ((Custom_SE)serverList.SelectedItem).Port; string addr = ((Custom_SE)serverList.SelectedItem).RealAddress; if (addr == "login.ultimaonline.com") { ClientCommunication.ServerEncrypted = true; } if (port == 0) { port = 2593; // runuo default } se = new ServerEntry(addr, port); } else if (!(serverList.SelectedItem is LoginCFG_SE)) { se = (ServerEntry)serverList.SelectedItem; se.Port = Utility.ToInt32(port.Text.Trim(), 0); if (se.Port <= 0 || se.Port > 65535) { MessageBox.Show(this, Language.GetString(LocString.NeedPort), "Need Port", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } } } else if (serverList.Text != "") { int thePort = Utility.ToInt32(port.Text.Trim(), 0); if (thePort <= 0 || thePort > 65535) { MessageBox.Show(this, Language.GetString(LocString.NeedPort), "Need Port", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } se = new ServerEntry(serverList.Text.Trim(), thePort); } if (se != null && se.Address != null) { if (!(serverList.SelectedItem is Custom_SE)) { serverList.Items.Remove(se); serverList.Items.Insert(1, se); } //if ( se.Address != "" ) // WriteLoginCFG( se.Address, se.Port ); Config.SetRegString(Registry.CurrentUser, "LastServer", se.Address); Config.SetRegString(Registry.CurrentUser, "LastPort", se.Port.ToString()); } SaveData(); this.Close(); }
private void ShowDetails(ServerEntry entry) { Model.ServerSelected = true; Frame.Source = UriExtension.Create("/Pages/Drive/OnlineServer.xaml?Id={0}", entry.Id); }
private App() { AppArguments.Set(AppFlag.SyncNavigation, ref ModernFrame.OptionUseSyncNavigation); AppArguments.Set(AppFlag.DisableTransitionAnimation, ref ModernFrame.OptionDisableTransitionAnimation); AppArguments.Set(AppFlag.RecentlyClosedQueueSize, ref LinkGroupFilterable.OptionRecentlyClosedQueueSize); AppArguments.Set(AppFlag.ForceSteamId, ref SteamIdHelper.OptionForceValue); 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.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.LiteStartupModeSupported, ref Pages.Windows.MainWindow.OptionLiteModeSupported); 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 += CurrentDomain_ProcessExit; 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); 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; } FancyBackgroundManager.Initialize(); DpiAwareWindow.OptionScale = AppArguments.GetDouble(AppFlag.UiScale, 1d); if (!AppKeyHolder.IsAllRight) { AppAppearanceManager.OptionCustomThemes = false; } else { AppArguments.Set(AppFlag.CustomThemes, ref AppAppearanceManager.OptionCustomThemes); } 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 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(); AppIconService.Initialize(this); Toast.SetDefaultAction(() => (Current.Windows.OfType <ModernWindow>().FirstOrDefault(x => x.IsActive) ?? Current.MainWindow as ModernWindow)?.BringToFront()); BbCodeBlock.ImageClicked += BbCodeBlock_ImageClicked; BbCodeBlock.OptionEmojiProvider = InternalUtils.GetEmojiProvider(); BbCodeBlock.OptionImageCacheDirectory = FilesStorage.Instance.GetTemporaryFilename("Images"); BbCodeBlock.OptionEmojiCacheDirectory = FilesStorage.Instance.GetTemporaryFilename("Emoji"); AppArguments.SetSize(AppFlag.ImagesCacheLimit, ref BetterImage.OptionCacheTotalSize); AppArguments.Set(AppFlag.ImagesMarkCached, ref BetterImage.OptionMarkCached); AppArguments.Set(AppFlag.UseVlcForAnimatedBackground, ref DynamicBackground.OptionUseVlc); Filter.OptionSimpleMatching = SettingsHolder.Content.SimpleFiltering; StartupUri = new Uri(!Superintendent.Instance.IsReady || AcRootDirectorySelector.IsReviewNeeded() ? @"Pages/Dialogs/AcRootDirectorySelector.xaml" : @"Pages/Windows/MainWindow.xaml", UriKind.Relative); 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(); }
public override int Compare(ServerEntry x, ServerEntry y) { var dif = -x.Capacity.CompareTo(y.Capacity); return(dif == 0 ? string.Compare(x.DisplayName, y.DisplayName, StringComparison.Ordinal) : dif); }
private App() { if (AppArguments.GetBool(AppFlag.IgnoreHttps)) { ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true; } ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; 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.WeatherExtMode, ref WeatherProceduralHelper.Option24HourMode); 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(); //#if !DEBUG Kn5.Factory = Kn5New.GetFactoryInstance(); //#endif 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); AppArguments.Set(AppFlag.HideRaceCancelButton, ref GameDialog.OptionHideCancelButton); AppArguments.Set(AppFlag.PatchSupport, ref PatchHelper.OptionPatchSupport); AppArguments.Set(AppFlag.CspReportsLocation, ref CspReportUtils.OptionLocation); AppArguments.Set(AppFlag.CmWorkshop, ref WorkshopClient.OptionUserAvailable); AppArguments.Set(AppFlag.CmWorkshopCreator, ref WorkshopClient.OptionCreatorAvailable); // 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); LocalizationHelper.Use12HrFormat = SettingsHolder.Common.Use12HrTimeFormat; 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(); CupViewModel.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://csp/enable"), new DelegateCommand(() => { using (var model = PatchSettingsModel.Create()) { var item = model.Configs? .FirstOrDefault(x => x.FileNameWithoutExtension == "general")?.Sections.GetByIdOrDefault("BASIC")? .GetByIdOrDefault("ENABLED"); if (item != null) { item.Value = @"1"; } } })); BbCodeBlock.AddLinkCommand(new Uri("cmd://csp/disable"), new DelegateCommand(() => { using (var model = PatchSettingsModel.Create()) { var item = model.Configs? .FirstOrDefault(x => x.FileNameWithoutExtension == "general")?.Sections.GetByIdOrDefault("BASIC")? .GetByIdOrDefault("ENABLED"); if (item != null) { item.Value = @"0"; } } })); BbCodeBlock.AddLinkCommand(new Uri("cmd://csp/update"), new DelegateCommand <string>(id => { var version = id.As(0); if (version == 0) { Logging.Error($"Wrong parameter: {id}"); return; } var versionInfo = PatchUpdater.Instance.Versions.FirstOrDefault(x => x.Build == version); if (versionInfo == null) { Logging.Error($"Version {version} is missing"); return; } PatchUpdater.Instance.InstallAsync(versionInfo, CancellationToken.None); })); 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)).Ignore(); })); BbCodeBlock.AddLinkCommand(new Uri("cmd://downloadMissing/track"), new DelegateCommand <string>(id => { var s = id.Split('|'); IndexDirectDownloader.DownloadTrackAsync(s[0], s.ArrayElementAtOrDefault(1)).Ignore(); })); BbCodeBlock.AddLinkCommand(new Uri("cmd://createNeutralLut"), new DelegateCommand <string>(id => NeutralColorGradingLut.CreateNeutralLut(id.As(16)))); BbCodeBlock.AddLinkCommand(new Uri("cmd://openPage/importantTips"), new DelegateCommand <string>(id => LinkCommands.NavigateLinkMainWindow.Execute(new Uri($"/Pages/About/ImportantTipsPage.xaml?Key={id}", UriKind.Relative)))); BbCodeBlock.AddLinkCommand(new Uri("cmd://openCarLodGeneratorDefinitions"), new DelegateCommand <string>(id => WindowsHelper.ViewFile(FilesStorage.Instance.GetContentFile(ContentCategory.CarLodsGeneration, "CommonDefinitions.json").Filename))); BbCodeBlock.AddLinkCommand(new Uri("cmd://findSrsServers"), new DelegateCommand(() => new ModernDialog { ShowTitle = false, ShowTopBlob = false, Title = "Connect to SimRacingSystem", Content = new ModernFrame { Source = new Uri("/Pages/Drive/Online.xaml?Filter=SimRacingSystem", UriKind.Relative) }, MinHeight = 400, MinWidth = 800, MaxHeight = DpiAwareWindow.UnlimitedSize, MaxWidth = DpiAwareWindow.UnlimitedSize, Padding = new Thickness(0), ButtonsMargin = new Thickness(8, -32, 8, 8), SizeToContent = SizeToContent.Manual, ResizeMode = ResizeMode.CanResizeWithGrip, LocationAndSizeKey = @".SrsJoinDialog" }.ShowDialog())); BbCodeBlock.DefaultLinkNavigator.PreviewNavigate += (sender, args) => { if (ArgumentsHandler.IsCmCommand(args.Uri)) { ArgumentsHandler.ProcessArguments(new[] { args.Uri.ToString() }, true).Ignore(); args.Cancel = true; } }; WorkshopLinkCommands.Initialize(); AppArguments.SetSize(AppFlag.ImagesCacheLimit, ref BetterImage.OptionCacheTotalSize); AppArguments.SetSize(AppFlag.CarLodGeneratorCacheSize, ref CarGenerateLodsDialog.OptionCacheSize); 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, false)) { 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(); // Make sure Steam is running if (SettingsHolder.Common.LaunchSteamAtStart) { LaunchSteam().Ignore(); } // Check and apply FTH fix if necessary CheckFaultTolerantHeap().Ignore(); RaceUTemporarySkinsHelper.Initialize(); // Initializing CSP handler if (PatchHelper.OptionPatchSupport) { PatchUpdater.Initialize(); } // Let’s roll ShutdownMode = ShutdownMode.OnExplicitShutdown; new AppUi(this).Run(() => { if (PatchHelper.OptionPatchSupport) { PatchUpdater.Instance.Updated += OnPatchUpdated; } }); }
static void Main(string[] args) { if (RaygunKey[0] != '{') { Raygun = new RaygunClient(RaygunKey); } AppDomain.CurrentDomain.UnhandledException += (sender, e) => { if (StartupLog != null) { StartupLog.Error("Fatal Error", (Exception)e.ExceptionObject); } if (Raygun != null) { Raygun.Send((Exception)e.ExceptionObject, null, Settings.CurrentSettings); } MessageBox.Show("Unexpected error" + Environment.NewLine + (e.ExceptionObject as Exception).ToDisplayString(), "Unexpected error", MessageBoxButtons.OK, MessageBoxIcon.Error); }; //AutomaticErrorReporter errors = new AutomaticErrorReporter(); //errors.Add (new GablarskiErrorReporter (typeof(Program).Assembly)); log4net.Config.XmlConfigurator.Configure(); StartupLog = LogManager.GetLogger("Startup"); StartupLog.DebugFormat("PID: {0}", Process.GetCurrentProcess().Id); FileInfo program = new FileInfo(Process.GetCurrentProcess().MainModule.FileName); Environment.CurrentDirectory = program.Directory.FullName; string useLocalValue = ConfigurationManager.AppSettings["useLocalDatabase"]; bool useLocal; Boolean.TryParse(useLocalValue, out useLocal); StartupLog.DebugFormat("Local files: {0}", useLocal); StartupLog.DebugFormat("Setting up databases.."); ClientData.Setup(useLocal); StartupLog.DebugFormat("Databases setup."); CheckForUpdates(); StartupLog.Debug("Starting key retrieval"); var keyCancelSource = new CancellationTokenSource(); Key = ClientData.GetCryptoKeyAsync(keyCancelSource.Token); Key.ContinueWith(t => StartupLog.DebugFormat("Key retrieval: {0}{1}{2}", t.Status, Environment.NewLine, t.Exception)); SetupFirstRun(); if (Settings.Nickname == null) { PersonalSetup(); } if (!ShowKeyProgress(keyCancelSource)) { return; } ResourceWebRequestFactory.Register(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //SetupSocial(); /*MainWindow window = new MainWindow(); * window.Show();*/ var m = new MainForm(); m.Show(); UpdateTaskbarServers(); if (args.Length > 0) { int id; if (Int32.TryParse(args[0], out id)) { ServerEntry server = Servers.GetEntries().FirstOrDefault(s => s.Id == id); if (server == null) { if (!m.ShowConnect(true)) { return; } } else { m.Connect(server); } } else { Uri server = new Uri(args[0]); m.Connect(server.Host, (server.Port != -1) ? server.Port : 42912); } } else if (Settings.ShowConnectOnStart) { if (!m.ShowConnect(true)) { return; } } /*System.Windows.Application app = new System.Windows.Application(); * app.Run (window);*/ Application.Run(m); Settings.Save(); }
public abstract int Compare(ServerEntry x, ServerEntry y);
public void DrawContent(int windowId) { GUILayout.BeginVertical(); GUI.DragWindow(MoveRect); GUILayout.Space(20); GUILayout.BeginHorizontal(); GUILayout.Label("Player Name:", LabelOptions); var oldPlayerName = SettingsSystem.CurrentSettings.PlayerName; SettingsSystem.CurrentSettings.PlayerName = GUILayout.TextArea(SettingsSystem.CurrentSettings.PlayerName, 32, TextAreaStyle); // Max 32 characters if (oldPlayerName != SettingsSystem.CurrentSettings.PlayerName) { SettingsSystem.CurrentSettings.PlayerName = SettingsSystem.CurrentSettings.PlayerName.Replace("\n", ""); RenameEventHandled = false; } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); //Draw add button var addMode = SelectedSafe == -1 ? "Add" : "Edit"; var buttonAddMode = addMode; if (AddingServer) { buttonAddMode = "Cancel"; } AddingServer = GUILayout.Toggle(AddingServer, buttonAddMode, ButtonStyle); if (AddingServer && !AddingServerSafe && Selected != -1) { //Load the existing server settings ServerName = SettingsSystem.CurrentSettings.Servers[Selected].Name; ServerAddress = SettingsSystem.CurrentSettings.Servers[Selected].Address; ServerPort = SettingsSystem.CurrentSettings.Servers[Selected].Port.ToString(); } //Draw connect button if (MainSystem.NetworkState == ClientState.Disconnected) { GUI.enabled = SelectedSafe != -1; if (GUILayout.Button("Connect", ButtonStyle)) { ConnectEventHandled = false; } } else if (MainSystem.NetworkState > ClientState.Disconnected) { if (GUILayout.Button("Disconnect", ButtonStyle)) { DisconnectEventHandled = false; } } //Draw remove button if (GUILayout.Button("Remove", ButtonStyle)) { if (RemoveEventHandled) { RemoveEventHandled = false; } } GUI.enabled = true; WindowsContainer.Get <OptionsWindow>().Display = GUILayout.Toggle(WindowsContainer.Get <OptionsWindow>().Display, "Options", ButtonStyle); if (GUILayout.Button("Servers", ButtonStyle)) { WindowsContainer.Get <ServerListWindow>().Display = true; } if (SettingsSystem.CurrentSettings.CloseBtnInConnectionWindow && GUILayout.Button("Close", ButtonStyle)) { Closed = true; } GUILayout.EndHorizontal(); if (AddingServerSafe) { GUILayout.BeginHorizontal(); GUILayout.Label("Name:", LabelOptions); ServerName = GUILayout.TextArea(ServerName, TextAreaStyle); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Address:", LabelOptions); ServerAddress = GUILayout.TextArea(ServerAddress, TextAreaStyle).Trim(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Port:", LabelOptions); ServerPort = GUILayout.TextArea(ServerPort, TextAreaStyle).Trim(); GUILayout.EndHorizontal(); if (GUILayout.Button($"{addMode} server", ButtonStyle)) { if (AddEventHandled) { if (Selected == -1) { AddEntry = new ServerEntry { Name = ServerName, Address = ServerAddress, Port = 8800 }; int.TryParse(ServerPort, out AddEntry.Port); AddEventHandled = false; } else { EditEntry = new ServerEntry { Name = ServerName, Address = ServerAddress, Port = 8800 }; int.TryParse(ServerPort, out EditEntry.Port); EditEventHandled = false; } } } } GUILayout.Label("Custom servers:"); if (SettingsSystem.CurrentSettings.Servers.Count == 0) { GUILayout.Label("(None - Add a server first)"); } ScrollPos = GUILayout.BeginScrollView(ScrollPos, GUILayout.Width(WindowWidth - 5), GUILayout.Height(WindowHeight - 100)); for (var serverPos = 0; serverPos < SettingsSystem.CurrentSettings.Servers.Count; serverPos++) { var thisSelected = GUILayout.Toggle(serverPos == SelectedSafe, SettingsSystem.CurrentSettings.Servers[serverPos].Name, ButtonStyle); if (Selected == SelectedSafe) { if (thisSelected) { if (Selected != serverPos) { Selected = serverPos; AddingServer = false; } } else if (Selected == serverPos) { Selected = -1; AddingServer = false; } } } GUILayout.EndScrollView(); //Draw Status Message GUILayout.Label(Status, StatusStyle); GUILayout.EndVertical(); }
public override int Compare(ServerEntry x, ServerEntry y) { var dif = -x.CurrentDriversCount.CompareTo(y.CurrentDriversCount); return(dif == 0 ? string.Compare(x.SortingName, y.SortingName, StringComparison.Ordinal) : dif); }
public void CreateServerEntry(string name, string hostname) { ServerEntry serverEntry = new ServerEntry(name, hostname); ServerEntries.Add(serverEntry); }
private void WelcomeForm_Load(object sender, System.EventArgs e) { Language.LoadControlNames( this ); this.BringToFront(); langSel.Items.AddRange( Language.GetPackNames() ); langSel.SelectedItem = Language.Current; showAtStart.Checked = Utility.ToInt32( Config.GetRegString( Microsoft.Win32.Registry.CurrentUser, "ShowWindow" ), 1 ) == 1; clientList.Items.Add( Language.GetString( LocString.Auto2D ) ); clientList.Items.Add( Language.GetString( LocString.Auto3D ) ); for (int i=1; ;i++) { string val = String.Format( "Client{0}", i ); string cli = Config.GetRegString( Microsoft.Win32.Registry.CurrentUser, val ); if ( cli == null || cli == "" ) break; if ( File.Exists( cli ) ) clientList.Items.Add( new PathElipsis( cli ) ); Config.DeleteRegValue( Microsoft.Win32.Registry.CurrentUser, val ); } int sel = Utility.ToInt32( Config.GetRegString( Microsoft.Win32.Registry.CurrentUser, "DefClient" ), 0 ); if ( sel >= clientList.Items.Count ) { sel = 0; Config.SetRegString( Microsoft.Win32.Registry.CurrentUser, "DefClient", "0" ); } clientList.SelectedIndex = sel; dataDir.Items.Add( Language.GetString( LocString.AutoDetect ) ); for ( int i=1; ;i++) { string val = String.Format( "Dir{0}", i ); string dir = Config.GetRegString( Microsoft.Win32.Registry.CurrentUser, val ); if ( dir == null || dir == "" ) break; if ( Directory.Exists( dir ) ) dataDir.Items.Add( dir ); Config.DeleteRegValue( Microsoft.Win32.Registry.CurrentUser, val ); } try { dataDir.SelectedIndex = Convert.ToInt32( Config.GetRegString( Microsoft.Win32.Registry.CurrentUser, "LastDir" ) ); } catch { dataDir.SelectedIndex = 0; } patchEncy.Checked = Utility.ToInt32( Config.GetRegString( Microsoft.Win32.Registry.CurrentUser, "PatchEncy" ), 1 ) != 0; useEnc.Checked = Utility.ToInt32( Config.GetRegString( Microsoft.Win32.Registry.CurrentUser, "ServerEnc" ), 0 ) != 0; LoginCFG_SE lse = new LoginCFG_SE(); UOGamers_SE uog; serverList.BeginUpdate(); //serverList.Items.Add( lse=new LoginCFG_SE() ); //serverList.SelectedItem = lse; for (int i=1; ;i++) { ServerEntry se; string sval = String.Format( "Server{0}", i ); string serv = Config.GetRegString( Microsoft.Win32.Registry.CurrentUser, sval ); if ( serv == null ) break; string pval = String.Format( "Port{0}", i ); int port = Utility.ToInt32( Config.GetRegString( Microsoft.Win32.Registry.CurrentUser, pval ), 0 ); serverList.Items.Add( se=new ServerEntry( serv, port ) ); if ( serv == lse.RealAddress && port == lse.Port ) serverList.SelectedItem = se; Config.DeleteRegValue( Microsoft.Win32.Registry.CurrentUser, sval ); Config.DeleteRegValue( Microsoft.Win32.Registry.CurrentUser, pval ); } serverList.Items.Add(uog = new UOGamers_SE("Zenvera (UOR)", "login.zenvera.com")); if (serverList.SelectedItem == null || lse.RealAddress == uog.RealAddress && lse.Port == 2593) serverList.SelectedItem = uog; serverList.Items.Add(uog = new UOGamers_SE("Second Age (T2A)", "login.uosecondage.com")); if (lse.RealAddress == uog.RealAddress && lse.Port == 2593) serverList.SelectedItem = uog; serverList.Items.Add(uog = new UOGamers_SE("An Corp (T2A)", "login.uoancorp.com")); if (lse.RealAddress == uog.RealAddress && lse.Port == 2593) serverList.SelectedItem = uog; serverList.Items.Add(uog = new UOGamers_SE("Forever (P16)", "login.uoforever.com", 2599)); if (lse.RealAddress == uog.RealAddress && lse.Port == 2599) serverList.SelectedItem = uog; serverList.Items.Add(uog = new UOGamers_SE("Pandora (HS)", "play.pandorauo.com")); if (lse.RealAddress == uog.RealAddress && lse.Port == 2593) serverList.SelectedItem = uog; serverList.Items.Add(uog = new UOGamers_SE("Electronic Arts/Origin Servers", "login.ultimaonline.com", 7775)); if ( lse.RealAddress == uog.RealAddress && ( lse.Port >= 7775 && lse.Port <= 7778 ) ) serverList.SelectedItem = uog; serverList.EndUpdate(); serverList.Refresh(); WindowState = FormWindowState.Normal; this.BringToFront(); this.TopMost = true; _ShowTimer = new System.Windows.Forms.Timer(); _ShowTimer.Interval = 250; _ShowTimer.Enabled = true; _ShowTimer.Tick += new EventHandler(timer_Tick); }
public void DrawContent(int windowId) { GUILayout.BeginVertical(); GUI.DragWindow(MoveRect); GUILayout.Space(20); GUILayout.BeginHorizontal(); GUILayout.Label(LocalizationContainer.ConnectionWindowText.PlayerName, LabelOptions); var oldPlayerName = SettingsSystem.CurrentSettings.PlayerName; SettingsSystem.CurrentSettings.PlayerName = GUILayout.TextArea(SettingsSystem.CurrentSettings.PlayerName, 32, TextAreaStyle); // Max 32 characters if (oldPlayerName != SettingsSystem.CurrentSettings.PlayerName) { SettingsSystem.CurrentSettings.PlayerName = SettingsSystem.CurrentSettings.PlayerName.Replace("\n", ""); RenameEventHandled = false; } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); //Draw add button var addMode = SelectedSafe == -1 ? LocalizationContainer.ConnectionWindowText.Add : LocalizationContainer.ConnectionWindowText.Edit; var buttonAddMode = addMode; if (AddingServer) { buttonAddMode = LocalizationContainer.ConnectionWindowText.Cancel; } AddingServer = GUILayout.Toggle(AddingServer, buttonAddMode, ButtonStyle); if (AddingServer && !AddingServerSafe && Selected != -1) { //Load the existing server settings ServerName = SettingsSystem.CurrentSettings.Servers[Selected].Name; ServerAddress = SettingsSystem.CurrentSettings.Servers[Selected].Address; ServerPort = SettingsSystem.CurrentSettings.Servers[Selected].Port.ToString(); Password = SettingsSystem.CurrentSettings.Servers[Selected].Password; } //Draw connect button if (MainSystem.NetworkState == ClientState.Disconnected) { GUI.enabled = SelectedSafe != -1; if (GUILayout.Button(LocalizationContainer.ConnectionWindowText.Connect, ButtonStyle)) { ConnectEventHandled = false; } } else if (MainSystem.NetworkState > ClientState.Disconnected) { if (GUILayout.Button(LocalizationContainer.ConnectionWindowText.Disconnect, ButtonStyle)) { DisconnectEventHandled = false; } } //Draw remove button if (GUILayout.Button(LocalizationContainer.ConnectionWindowText.Remove, ButtonStyle)) { if (RemoveEventHandled) { RemoveEventHandled = false; } } GUI.enabled = true; OptionsWindow.Singleton.Display = GUILayout.Toggle(OptionsWindow.Singleton.Display, LocalizationContainer.ConnectionWindowText.Options, ButtonStyle); if (GUILayout.Button(LocalizationContainer.ConnectionWindowText.Servers, ButtonStyle)) { ServerListWindow.Singleton.Display = true; } if (SettingsSystem.CurrentSettings.CloseBtnInConnectionWindow && GUILayout.Button(LocalizationContainer.ConnectionWindowText.Close, ButtonStyle)) { Closed = true; } GUILayout.EndHorizontal(); if (AddingServerSafe) { GUILayout.BeginHorizontal(); GUILayout.Label(LocalizationContainer.ConnectionWindowText.Name, LabelOptions); ServerName = GUILayout.TextArea(ServerName, TextAreaStyle); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label(LocalizationContainer.ConnectionWindowText.Address, LabelOptions); ServerAddress = GUILayout.TextArea(ServerAddress, TextAreaStyle).Trim(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label(LocalizationContainer.ConnectionWindowText.Port, LabelOptions); ServerPort = GUILayout.TextArea(ServerPort, TextAreaStyle).Trim(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label(LocalizationContainer.ConnectionWindowText.Password, LabelOptions); Password = GUILayout.TextArea(Password, TextAreaStyle).Trim(); GUILayout.EndHorizontal(); if (GUILayout.Button($"{addMode} {LocalizationContainer.ConnectionWindowText.Server}", ButtonStyle)) { if (AddEventHandled) { if (Selected == -1) { AddEntry = new ServerEntry { Name = ServerName, Address = ServerAddress, Port = 8800, Password = Password }; int.TryParse(ServerPort, out AddEntry.Port); AddEventHandled = false; } else { EditEntry = new ServerEntry { Name = ServerName, Address = ServerAddress, Port = 8800, Password = Password }; int.TryParse(ServerPort, out EditEntry.Port); EditEventHandled = false; } } } } GUILayout.Label(LocalizationContainer.ConnectionWindowText.CustomServers); if (SettingsSystem.CurrentSettings.Servers.Count == 0) { GUILayout.Label(LocalizationContainer.ConnectionWindowText.NoServers); } ScrollPos = GUILayout.BeginScrollView(ScrollPos, GUILayout.Width(WindowWidth - 5), GUILayout.Height(WindowHeight - 100)); for (var serverPos = 0; serverPos < SettingsSystem.CurrentSettings.Servers.Count; serverPos++) { var thisSelected = GUILayout.Toggle(serverPos == SelectedSafe, SettingsSystem.CurrentSettings.Servers[serverPos].Name, ButtonStyle); if (Selected == SelectedSafe) { if (thisSelected) { if (Selected != serverPos) { Selected = serverPos; AddingServer = false; } } else if (Selected == serverPos) { Selected = -1; AddingServer = false; } } } GUILayout.EndScrollView(); //Draw Status Message GUILayout.Label(Status, StatusStyle); GUILayout.EndVertical(); }