Esempio n. 1
0
        public static int Main(string[] args)
        {
            try {
                Trace.Listeners.Add(new ConsoleTraceListener());
                FileUtils.TryToDelete(Path.Combine(MainExecutingFile.Directory, "Log.txt"));
                Trace.Listeners.Add(new DefaultTraceListener {
                    LogFileName = Path.Combine(MainExecutingFile.Directory, "Log.txt")
                });

                var argsLoaded = false;
                if (args.Length > 0)
                {
                    try {
                        if (File.Exists(args[0]))
                        {
                            var extraFileArgs = Path.Combine(Path.GetDirectoryName(args[0]) ?? ".", "Baked Shadows Params.txt");
                            if (File.Exists(extraFileArgs))
                            {
                                args = File.ReadAllLines(extraFileArgs).Where(x => !string.IsNullOrWhiteSpace(x) && !x.TrimStart().StartsWith("#"))
                                       .Union(args).ToArray();
                                argsLoaded = true;
                            }
                            else
                            {
                                extraFileArgs = Path.Combine(Path.GetDirectoryName(args[0]) ?? ".", "Baked_Shadows_Params.txt");
                                if (File.Exists(extraFileArgs))
                                {
                                    args = File.ReadAllLines(extraFileArgs).Where(x => !string.IsNullOrWhiteSpace(x) && !x.TrimStart().StartsWith("#"))
                                           .Union(args).ToArray();
                                    argsLoaded = true;
                                }
                            }
                        }
                    } catch {
                        // ignored
                    }
                }

                if (!argsLoaded)
                {
                    var extraArgs = Path.Combine(MainExecutingFile.Directory, "Arguments.txt");
                    if (File.Exists(extraArgs))
                    {
                        args = File.ReadAllLines(extraArgs).Where(x => !string.IsNullOrWhiteSpace(x) && !x.TrimStart().StartsWith("#"))
                               .Union(args).ToArray();
                    }
                }

                var options = new Options();
                if (!Parser.Default.ParseArguments(args, options) || options.Items.Count == 0 || options.Help)
                {
                    Trace.WriteLine(options.GetUsage());
                    return(options.Help ? 0 : 1);
                }

                string mainKn5 = null;
                string destination;
                var    includeKn5   = new List <string>();
                var    occludersKn5 = new List <string>();

                if (options.Items[0].EndsWith(".ini"))
                {
                    var ini            = new IniFile(options.Items[0]);
                    var trackDirectory = Path.GetDirectoryName(ini.Filename) ?? ".";
                    var first          = true;
                    includeKn5.Clear();
                    occludersKn5.Clear();
                    foreach (var model in ini.GetSections("MODEL").Select(x => x.GetNonEmpty("FILE")).NonNull()
                             .Select(x => Path.Combine(trackDirectory, x)).Where(File.Exists))
                    {
                        if (first)
                        {
                            first   = false;
                            mainKn5 = model;
                        }
                        else
                        {
                            includeKn5.Add(model);
                        }
                    }

                    destination = Path.Combine(trackDirectory, Path.GetFileNameWithoutExtension(ini.Filename) + ".vao-patch");
                }
                else
                {
                    mainKn5     = options.Items[0];
                    destination = options.Destination ?? options.Items[0];
                    var trackDirectory = Path.GetDirectoryName(mainKn5) ?? ".";

                    if (!options.ModifyKn5Directly)
                    {
                        if (!string.IsNullOrWhiteSpace(options.IncludeKn5Filter))
                        {
                            var includeFilter = Filter.Create(StringTester.Instance, options.IncludeKn5Filter,
                                                              new FilterParams {
                                StringMatchMode = StringMatchMode.CompleteMatch
                            });
                            foreach (var file in Directory.GetFiles(trackDirectory, "*.kn5").Where(x =>
                                                                                                   includeFilter.Test(Path.GetFileName(x)) && !FileUtils.ArePathsEqual(x, mainKn5)))
                            {
                                includeKn5.Add(file);

                                destination = Path.Combine(trackDirectory, Path.GetFileName(trackDirectory)) + ".kn5";
                            }
                        }
                    }

                    if (!string.IsNullOrWhiteSpace(options.OccludersKn5Filter ?? options.CommonKn5Filter))
                    {
                        var occludersFilter = Filter.Create(StringTester.Instance, options.OccludersKn5Filter ?? options.CommonKn5Filter,
                                                            new FilterParams {
                            StringMatchMode = StringMatchMode.CompleteMatch
                        });
                        foreach (var file in Directory.GetFiles(trackDirectory, "*.kn5").Where(x =>
                                                                                               occludersFilter.Test(Path.GetFileName(x)) && !FileUtils.ArePathsEqual(x, mainKn5)))
                        {
                            occludersKn5.Add(file);
                        }
                    }
                }

                if (mainKn5 == null)
                {
                    throw new Exception("Main KN5 not found");
                }

                using (var bakery = new MainBakery(mainKn5, options.Filter, options.IgnoreFilter, !options.ModifyKn5Directly)
                {
                    AoOpacity = options.AoOpacity,
                    AoMultiplier = options.AoMultiplier,
                    SaturationGain = options.SaturationGain,
                    SaturationInputMultiplier = options.SaturationInputMultiplier,
                    CameraFov = options.CameraFov,
                    CameraNear = options.CameraNear,
                    CameraFar = options.CameraFar,
                    CameraNormalOffsetUp = options.CameraNormalOffsetUp,
                    CameraOffsetAway = options.CameraOffsetAway,
                    CameraOffsetUp = options.CameraOffsetUp,
                    OccludersDistanceThreshold = options.OccludersDistanceThreshold,
                    MergeVertices = options.MergeVertices,
                    MergeThreshold = options.MergeThreshold,
                    OccludersSplitThreshold = options.OccludersSplitThreshold,
                    QueueSize = options.QueueSize,
                    SampleResolution = options.SampleResolution,
                    ExtraPassBrightnessGain = options.ExtraPassBrightnessGain,
                    HdrSamples = options.HdrSamples,
                    Ground = !options.NoGround,
                    SyncNormalsFilter = options.SyncNormals,
                    SyncNormalsPartiallyFilter = options.SyncNormalsPartially,
                    SyncNormalsPartiallyValue = options.SyncNormalsPartiallyValue,
                    ExtraPass = options.ExtraPass,
                    TreeFilter = options.TreeFilter,
                    GrassFilter = options.GrassFilter,
                    RegularObjectsFilter = options.RegularObjectsFilter,
                    SkipOccludersFilter = options.SkipOccludersFilter,
                    SpecialGrassAmbient = !options.NoSpecialGrassAmbient,
                    SurfacesFilter = options.Surfaces,
                    SurfacesAoOpacity = options.SurfacesAoOpacity,
                    SetMiltiplierForSkipped = options.SetMiltiplierForSkipped,
                }) {
                    if (!string.IsNullOrWhiteSpace(options.DebugPos))
                    {
                        bakery.DebugMode  = true;
                        bakery.DebugPoint = options.DebugPos.Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries)
                                            .Select(x => (float)FlexibleParser.ParseDouble(x))
                                            .ToArray().ToVector3();
                        bakery.DebugRadius = options.DebugRange;
                        Console.WriteLine("Debug mode: " + bakery.DebugPoint);
                    }

                    bakery.LoadExtraKn5(includeKn5, occludersKn5).Work(destination);
                }

                Trace.Listeners.Clear();
                return(0);
            } catch (Exception e) {
                Trace.WriteLine(e.ToString());
                return(2);
            } finally {
                if (ParentProcessUtilities.GetParentProcess().ProcessName == "explorer")
                {
                    Console.ReadLine();
                }
            }
        }
Esempio n. 2
0
        public TimeSpan GuessApproximateLapDuration(CarObject car = null)
        {
            var averageSpeed = ((FlexibleParser.TryParseDouble(car?.SpecsTopSpeed) ?? 200d) * 0.3).Clamp(20d, 200d);

            return(TimeSpan.FromHours(SpecsLengthValue / 1e3 / averageSpeed).Clamp(TimeSpan.FromSeconds(30), TimeSpan.FromHours(2)));
        }
Esempio n. 3
0
 internal NumberTestEntry(Operator op, [NotNull] string originalValue)
 {
     _op            = op;
     _originalValue = originalValue;
     _value         = FlexibleParser.TryParseDouble(originalValue, out var num) ? num : double.NaN;
 }
Esempio n. 4
0
        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();
            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);

            // 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);
                }
            }

            Storage.TemporaryBackupsDirectory = FilesStorage.Instance.GetTemporaryDirectory("Storages Backups");
            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();
        }
Esempio n. 5
0
        protected override void ParseString(string data)
        {
            Clear();

            var started   = -1;
            var key       = double.NaN;
            var malformed = -1;
            var line      = 1;

            for (var i = 0; i < data.Length; i++)
            {
                switch (data[i])
                {
                case '\r':
                    if (i + 1 < data.Length)
                    {
                        var next = data[i + 1];
                        if (next == '\n' || next == '\r')
                        {
                            continue;
                        }
                    }

                    AcToolsLogging.Write($@"Unexpected “\r” at {line}");
                    malformed = line;
                    break;

                case '|':
                    if (started != -1)
                    {
                        if (!double.IsNaN(key) || !FlexibleParser.TryParseDouble(data.Substring(started, i - started), out key))
                        {
                            if (malformed == -1)
                            {
                                if (!double.IsNaN(key))
                                {
                                    AcToolsLogging.Write($@"Key already defined! But then, there is a second one, at {line}");
                                }
                                else
                                {
                                    AcToolsLogging.Write($@"Failed to parse key “{data.Substring(started, i - started)}” at {line}");
                                }

                                malformed = line;
                            }

                            SkipLine(data, ref i, ref line);
                            key = double.NaN;
                        }
                        started = -1;
                    }
                    break;

                case '\n':
                    Finish(Values, data, i, line, ref key, ref started, ref malformed);
                    line++;
                    break;

                case '/':
                    if (i + 1 < data.Length && data[i + 1] == '/')
                    {
                        goto case ';';
                    }
                    goto default;

                case ';':
                    Finish(Values, data, i, line, ref key, ref started, ref malformed);
                    SkipLine(data, ref i, ref line);
                    break;

                default:
                    if (started == -1)
                    {
                        started = i;
                    }
                    break;
                }
            }

            Finish(Values, data, data.Length, line, ref key, ref started, ref malformed);

            if (malformed != -1)
            {
                ErrorsCatcher?.Catch(this, malformed);
            }
        }
Esempio n. 6
0
        public static Color GetColor(this IniFileSection section, [LocalizationRequired(false)] string key, Color defaultValue)
        {
            var result = section.GetStrings(key).Select(x => FlexibleParser.ParseInt(x, 0).ClampToByte()).ToArray();

            return(result.Length == 3 ? Color.FromRgb(result[0], result[1], result[2]) : defaultValue);
        }
Esempio n. 7
0
        public async Task <ArgumentHandleResult> ProgressRaceOnlineJoin(NameValueCollection p)
        {
            /* required arguments */
            var ip                = p.Get(@"ip");
            var httpPort          = FlexibleParser.TryParseInt(p.Get(@"httpPort"));
            var password          = p.Get(@"plainPassword");
            var encryptedPassword = p.Get(@"password");

            if (string.IsNullOrWhiteSpace(ip))
            {
                throw new InformativeException("IP is missing");
            }

            if (!httpPort.HasValue)
            {
                throw new InformativeException("HTTP port is missing or is in invalid format");
            }

            OnlineManager.EnsureInitialized();

            if (string.IsNullOrWhiteSpace(password) && !string.IsNullOrWhiteSpace(encryptedPassword))
            {
                password = OnlineServer.DecryptSharedPassword(ip, httpPort.Value, encryptedPassword);
            }

            var list    = OnlineManager.Instance.List;
            var source  = new FakeSource(ip, httpPort.Value);
            var wrapper = new OnlineSourceWrapper(list, source);

            ServerEntry server;

            using (var waiting = new WaitingDialog()) {
                waiting.Report(ControlsStrings.Common_Loading);

                await wrapper.EnsureLoadedAsync();

                server = list.GetByIdOrDefault(source.Id);
                if (server == null)
                {
                    throw new Exception(@"Unexpected");
                }
            }

            if (password != null)
            {
                server.Password = password;
            }

            var content = new OnlineServer(server)
            {
                Margin  = new Thickness(0, 0, 0, -43),
                ToolBar = { FitWidth = true },

                // Values taken from ModernDialog.xaml
                // TODO: Extract them to some style?
                Title = { FontSize = 24, FontWeight = FontWeights.Light, Margin = new Thickness(6, 0, 0, 8) }
            };

            content.Title.SetValue(TextOptions.TextFormattingModeProperty, TextFormattingMode.Ideal);

            var dlg = new ModernDialog {
                ShowTitle          = false,
                Content            = content,
                MinHeight          = 400,
                MinWidth           = 450,
                MaxHeight          = 99999,
                MaxWidth           = 700,
                Padding            = new Thickness(0),
                ButtonsMargin      = new Thickness(8),
                SizeToContent      = SizeToContent.Manual,
                ResizeMode         = ResizeMode.CanResizeWithGrip,
                LocationAndSizeKey = @".OnlineServerDialog"
            };

            dlg.SetBinding(Window.TitleProperty, new Binding {
                Path   = new PropertyPath(nameof(server.DisplayName)),
                Source = server
            });

            dlg.ShowDialog();
            await wrapper.ReloadAsync(true);

            return(ArgumentHandleResult.Successful);
        }
Esempio n. 8
0
        public async Task <ArgumentHandleResult> ProgressRaceOnline(NameValueCollection p)
        {
            /* required arguments */
            var ip       = p.Get(@"ip");
            var port     = FlexibleParser.TryParseInt(p.Get(@"port"));
            var httpPort = FlexibleParser.TryParseInt(p.Get(@"httpPort"));
            var carId    = p.Get(@"car");

            /* optional arguments */
            var allowWithoutSteamId = p.GetFlag("allowWithoutSteamId");
            var carSkinId           = p.Get(@"skin");
            var trackId             = p.Get(@"track");
            var name              = p.Get(@"name");
            var nationality       = p.Get(@"nationality");
            var password          = p.Get(@"plainPassword");
            var encryptedPassword = p.Get(@"password");

            if (string.IsNullOrWhiteSpace(ip))
            {
                throw new InformativeException("IP is missing");
            }

            if (!port.HasValue)
            {
                throw new InformativeException("Port is missing or is in invalid format");
            }

            if (!httpPort.HasValue)
            {
                throw new InformativeException("HTTP port is missing or is in invalid format");
            }

            if (string.IsNullOrWhiteSpace(password) && !string.IsNullOrWhiteSpace(encryptedPassword))
            {
                password = OnlineServer.DecryptSharedPassword(ip, httpPort.Value, encryptedPassword);
            }

            if (string.IsNullOrWhiteSpace(carId))
            {
                throw new InformativeException("Car ID is missing");
            }

            var car = CarsManager.Instance.GetById(carId);

            if (car == null)
            {
                throw new InformativeException("Car is missing");
            }

            if (!string.IsNullOrWhiteSpace(carSkinId) && car.GetSkinById(carSkinId) == null)
            {
                throw new InformativeException("Car skin is missing");
            }

            var track = string.IsNullOrWhiteSpace(trackId) ? null : TracksManager.Instance.GetLayoutByKunosId(trackId);

            if (!string.IsNullOrWhiteSpace(trackId) && track == null)
            {
                throw new InformativeException("Track is missing");
            }


            if (!SteamIdHelper.Instance.IsReady && !allowWithoutSteamId)
            {
                throw new InformativeException(ToolsStrings.Common_SteamIdIsMissing);
            }

            await GameWrapper.StartAsync(new Game.StartProperties {
                BasicProperties = new Game.BasicProperties {
                    CarId   = carId,
                    TrackId = track?.MainTrackObject.Id ?? @"imola",
                    TrackConfigurationId = track?.LayoutId,
                    CarSkinId            = carSkinId,
                    DriverName           = name,
                    DriverNationality    = nationality
                },
                ModeProperties = new Game.OnlineProperties {
                    Guid           = SteamIdHelper.Instance.Value,
                    ServerIp       = ip,
                    ServerPort     = port.Value,
                    ServerHttpPort = httpPort.Value,
                    Password       = password,
                    RequestedCar   = carId
                }
            });

            return(ArgumentHandleResult.Successful);
        }
Esempio n. 9
0
        private static double GetDouble(JObject j, string key, double defaultValue = 0d)
        {
            var s = j.GetStringValueOnly(key);

            return(s == null ? defaultValue : FlexibleParser.TryParseDouble(s) ?? defaultValue);
        }
Esempio n. 10
0
        private static int MainInner(string[] args)
        {
            Acd.Factory = new AcdFactory();

            var presets    = args.Where(x => x.EndsWith(".pu-preset")).ToList();
            var actualList = new List <string>();

            foreach (var preset in presets)
            {
                try {
                    actualList.AddRange(
                        File.ReadAllLines(preset)
                        .Where(x => !x.StartsWith("#"))
                        .Select(x => x.Split(new[] { " #" }, StringSplitOptions.None)[0].Trim())
                        .Where(x => x.Length > 0));
                } catch (Exception e) {
                    Console.Error.WriteLine($"Can't load preset {preset}: {e.Message}.");
                }
            }

            actualList.AddRange(args.ApartFrom(presets));

            var options = new Options();

            if (!Parser.Default.ParseArguments(actualList.ToArray(), options))
            {
                return(1);
            }

            if (options.ColorGradingFilename != null && presets.Count > 0 && !File.Exists(options.ColorGradingFilename))
            {
                var locations = presets.Select(Path.GetDirectoryName).ToList();
                var current   = Environment.CurrentDirectory;
                foreach (var location in locations)
                {
                    Environment.CurrentDirectory = location;
                    var path = Path.GetFullPath(options.ColorGradingFilename);
                    if (File.Exists(path))
                    {
                        options.ColorGradingFilename = path;
                    }
                }

                Environment.CurrentDirectory = current;
            }

            var acRoot = options.AcRoot == null?AcRootFinder.TryToFind() : Path.GetFullPath(options.AcRoot);

            if (acRoot == null)
            {
                Console.Error.WriteLine("Can't find AC root directory, you need to specify it manually.");
                Console.ReadLine();
                return(1);
            }

            var ids = options.Ids.ApartFrom(presets).ToList();

            if (ids.Count == 0)
            {
                Console.Error.WriteLine("You forgot to specify what cars to update: either list their IDs or filters.");
                Console.Error.WriteLine("To process all cars, use filter \"*\".");
                Console.ReadLine();
                return(1);
            }

            IFilter <string> filter;

            try {
                filter = Filter.Create(new CarTester(acRoot), ids.Select(x =>
                                                                         "(" + (x.EndsWith("/") ? x.Substring(0, x.Length - 1) : x) + ")").JoinToString("|"), true);
                if (options.FilterTest)
                {
                    Console.WriteLine(Directory.GetDirectories(AcPaths.GetCarsDirectory(acRoot))
                                      .Select(Path.GetFileName).Where(x => filter.Test(x)).JoinToString(", "));
                    return(0);
                }

                if (options.Verbose)
                {
                    Console.WriteLine("Filter: " + filter);
                }
            } catch (Exception e) {
                Console.Error.WriteLine("Can't parse filter: " + e.Message + ".");
                Console.ReadLine();
                return(2);
            }

            if (options.Verbose)
            {
                Console.WriteLine("AC root: " + acRoot);
                Console.WriteLine("ImageMagick: " + ImageUtils.IsMagickSupported);
                Console.WriteLine("Starting shoting...");
            }

            var sw = Stopwatch.StartNew();
            int i = 0, j = 0;

            using (var thing = new DarkPreviewsUpdater(acRoot, new DarkPreviewsOptions {
                PreviewName = options.FileName,
                Showroom = options.Showroom,
                AlignCar = options.AlignCar,
                AlignCameraHorizontally = options.AlignCamera,
                AlignCameraHorizontallyOffset = options.AlignCameraOffset.Split(',').Select(x => FlexibleParser.TryParseDouble(x) ?? 0d).ToArray()[0], // TODO
                SsaaMultiplier = options.SsaaMultiplier,
                UseFxaa = options.UseFxaa,
                UseMsaa = options.UseMsaa,
                SoftwareDownsize = options.SoftwareDownsize,
                MsaaSampleCount = options.MsaaSampleCount,
                PreviewWidth = options.PreviewWidth,
                PreviewHeight = options.PreviewHeight,
                BloomRadiusMultiplier = options.BloomRadiusMultiplier,
                FlatMirror = options.FlatMirror,
                WireframeMode = options.WireframeMode,
                MeshDebugMode = options.MeshDebugMode,
                SuspensionDebugMode = options.SuspensionDebugMode,
                HeadlightsEnabled = options.HeadlightsEnabled,
                BrakeLightsEnabled = options.BrakeLightsEnabled,
                LeftDoorOpen = options.LeftDoorOpen,
                RightDoorOpen = options.RightDoorOpen,
                SteerDeg = options.SteerAngle,
                CameraPosition = options.CameraPosition.Split(',').Select(x => FlexibleParser.TryParseDouble(x) ?? 0d).ToArray(),
                CameraLookAt = options.LookAt.Split(',').Select(x => FlexibleParser.TryParseDouble(x) ?? 0d).ToArray(),
                CameraFov = options.Fov,
                BackgroundColor = ParseColor(options.BackgroundColor),
                LightColor = ParseColor(options.LightColor),
                AmbientUp = ParseColor(options.AmbientUp),
                AmbientDown = ParseColor(options.AmbientDown),
                AmbientBrightness = options.AmbientBrightness,
                LightBrightness = options.LightBrightness,
                DelayedConvertation = !options.SingleThread,
                UseSslr = options.UseSslr,
                UseAo = options.UseSsao,
                UsePcss = options.UsePcss,
                EnableShadows = options.EnableShadows,
                ShadowMapSize = options.ShadowMapSize,
                MaterialsReflectiveness = options.ReflectionMultiplier,
                ReflectionCubemapAtCamera = options.ReflectionCubemapAtCamera,
                ReflectionsWithShadows = !options.NoShadowsWithReflections,
                FlatMirrorBlurred = options.FlatMirrorBlurred,
                FlatMirrorReflectiveness = options.FlatMirrorReflectiveness,
                LightDirection = options.LightDirection.Split(',').Select(x => FlexibleParser.TryParseDouble(x) ?? 0d).ToArray(),
            })) {
                foreach (var carId in Directory.GetDirectories(AcPaths.GetCarsDirectory(acRoot))
                         .Select(Path.GetFileName).Where(x => filter.Test(x)))
                {
                    Console.WriteLine($"  {carId}...");
                    j++;

                    foreach (var skinId in Directory.GetDirectories(AcPaths.GetCarSkinsDirectory(acRoot, carId))
                             .Where(x => !options.WithoutPreviews || !File.Exists(Path.Combine(x, options.FileName)))
                             .Select(Path.GetFileName))
                    {
                        var success = false;
                        for (var a = 0; a < options.AttemptsCount || a == 0; a++)
                        {
                            try {
                                if (options.Verbose)
                                {
                                    Console.Write($"    {skinId}... ");
                                }
                                thing.Shot(carId, skinId);
                                success = true;
                                break;
                            } catch (Exception e) {
                                Console.Error.WriteLine(e.Message);

                                if (options.Verbose)
                                {
                                    Console.Error.WriteLine(e.StackTrace);
                                }
                            }
                        }

                        if (success)
                        {
                            i++;
                            if (options.Verbose)
                            {
                                Console.WriteLine("OK");
                            }
                        }
                    }

                    if (options.Verbose && j % 10 == 0)
                    {
                        Console.WriteLine(
                            $"At this moment done: {i} skins ({sw.Elapsed.TotalMilliseconds / j:F1} ms per car; {sw.Elapsed.TotalMilliseconds / i:F1} ms per skin)");
                        Console.WriteLine($"Time taken: {ToMillisecondsString(sw.Elapsed)}");
                    }
                }

                Console.Write("Finishing convertation... ");
            }

            Console.WriteLine("OK");
            Console.WriteLine($"Done: {i} skins ({sw.Elapsed.TotalMilliseconds / j:F1} ms per car; {sw.Elapsed.TotalMilliseconds / i:F1} ms per skin)");
            Console.WriteLine($"Time taken: {ToMillisecondsString(sw.Elapsed)}");

            return(0);
        }
Esempio n. 11
0
            private async Task LoadSpecs(CarObject value)
            {
                var acc = FlexibleParser.ParseDouble(value.SpecsAcceleration, 100);

                AccelerationValue = acc < 0.1 ? (double?)null : 1.0 - (acc - 2.0) / 10.0;
                TopSpeedValue     = (FlexibleParser.TryParseDouble(value.SpecsTopSpeed) - 150) / 200;
                WeightValue       = 1.0 - (FlexibleParser.TryParseDouble(value.SpecsWeight) - 600) / 1200;

                var tyres = await Task.Run(() => value.AcdData.GetIniFile("tyres.ini"));

                var tyresNames = tyres.Values.Select(x => x.GetNonEmpty("NAME")).Where(x => x != null).Distinct().ToList();

                Tyres = tyresNames.JoinToString(", ");

                var handlingValue = 0d;

                foreach (var name in tyresNames)
                {
                    switch (name.ToLowerInvariant())
                    {
                    case "michelin xas":
                        handlingValue = Math.Max(handlingValue, 0.1);
                        break;

                    case "street70s":
                    case "street 70s":
                        handlingValue = Math.Max(handlingValue, 0.2);
                        break;

                    case "cinturato":
                    case "vintage":
                    case "street90s":
                    case "street 90s":
                        handlingValue = Math.Max(handlingValue, 0.3);
                        break;

                    case "street":
                    case "modern street":
                        handlingValue = Math.Max(handlingValue, 0.4);
                        break;

                    case "semislick":
                    case "semislicks":
                        handlingValue = Math.Max(handlingValue, 0.5);
                        break;

                    case "slick hard":
                        handlingValue = Math.Max(handlingValue, 0.6);
                        break;

                    case "slick medium":
                        handlingValue = Math.Max(handlingValue, 0.7);
                        break;

                    case "slicks":
                    case "slick soft":
                        handlingValue = Math.Max(handlingValue, 0.8);
                        break;

                    case "hypercar trofeo":
                        handlingValue = Math.Max(handlingValue, 0.9);
                        break;
                    }
                }

                HandlingValue = handlingValue * (0.8 + 0.4 * (WeightValue ?? 0d));
            }
Esempio n. 12
0
        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();
        }
Esempio n. 13
0
        public static async Task <TimeZoneInfo> DetermineTimeZoneAsync(GeoTagsEntry geoTags)
        {
            var requestUri = string.Format(RequestTimeZoneUri, geoTags.LatitudeValue, geoTags.LongitudeValue,
                                           InternalUtils.GetTimeZoneDbApiCode());

            #if DEBUG
            Logging.Debug(requestUri);
            #endif

            using (var order = KillerOrder.Create(new CookieAwareWebClient(), 15000)) {
                var data = await order.Victim.DownloadStringTaskAsync(requestUri);

                var doc    = JObject.Parse(data);
                var zoneId = doc.GetStringValueOnly("zoneName");
                if (zoneId == null)
                {
                    throw new Exception("Invalid response");
                }

                Logging.Write("Returned zone ID: " + zoneId);

                try {
                    Logging.Write("Parsed as: " + TZConvert.GetTimeZoneInfo(zoneId).ToSerializedString());
                    return(TZConvert.GetTimeZoneInfo(zoneId));
                } catch (TimeZoneNotFoundException) {
                    var rawOffset = doc.GetStringValueOnly(@"gmtOffset");
                    return(TimeZoneInfo.CreateCustomTimeZone(zoneId, TimeSpan.FromSeconds(FlexibleParser.ParseDouble(rawOffset)), zoneId, zoneId));
                }
            }

            /*var requestUri = string.Format(RequestTimeZoneUri, geoTags.LatitudeValue, geoTags.LongitudeValue,
             *                             DateTime.Now.ToUnixTimestamp(), InternalUtils.GetGoogleMapsApiCode());
             *
             * using (var order = KillerOrder.Create(new WebClient(), 5000)) {
             *  var data = await order.Victim.DownloadStringTaskAsync(requestUri);
             *  var doc = XDocument.Parse(data);
             *  var zoneId = doc.Descendants(@"time_zone_id").FirstOrDefault()?.Value;
             *  if (zoneId == null) throw new Exception("Invalid response");
             *
             *  try {
             *      return TZConvert.GetTimeZoneInfo(zoneId);
             *  } catch (TimeZoneNotFoundException) {
             *      var rawOffset = doc.Descendants(@"raw_offset").FirstOrDefault()?.Value;
             *      var zoneName = doc.Descendants(@"time_zone_name").FirstOrDefault()?.Value;
             *      if (rawOffset == null || zoneName == null) throw new Exception("Invalid response");
             *      return TimeZoneInfo.CreateCustomTimeZone(zoneId, TimeSpan.FromSeconds(FlexibleParser.ParseDouble(rawOffset)), zoneName, zoneName);
             *  }
             * }*/
        }
Esempio n. 14
0
 public bool Test(string value)
 {
     return(value != null && (ToTimeSpan(value, _defaultPostfix, out var parsed, out var _) ? Test(parsed)
             : FlexibleParser.TryParseInt(value, out var val) && Test(val)));
 }
Esempio n. 15
0
        private static PythonAppConfigValue CreateInner(KeyValuePair <string, string> pair, [CanBeNull] string commentary, [CanBeNull] ref string name,
                                                        [CanBeNull] ref string toolTip, [CanBeNull] ref Func <IPythonAppConfigValueProvider, bool> isEnabledTest)
        {
            var value = pair.Value;

            if (commentary != null)
            {
                var match = ValueCommentaryRegex.Match(commentary);
                if (match.Success)
                {
                    name    = PythonAppConfig.CapitalizeFirst(match.Groups[1].Value.TrimEnd());
                    toolTip = match.Groups[2].Success ? PythonAppConfig.CapitalizeFirst(match.Groups[2].Value.Replace(@"; ", ";\n")) : null;

                    if (name.Length > 50 && toolTip == null)
                    {
                        toolTip = name;
                        name    = null;
                    }

                    if (match.Groups[3].Success)
                    {
                        var description = match.Groups[3].Value.Trim();

                        var dependent = DependentRegex.Match(description);
                        if (dependent.Success)
                        {
                            description   = dependent.Groups[1].Value;
                            isEnabledTest = CreateDisabledFunc(dependent.Groups[4].Value.Trim(), dependent.Groups[2].Success);
                        }

                        if (NumberRegex.IsMatch(description))
                        {
                            return(new PythonAppConfigNumberValue());
                        }

                        var boolean = BooleanRegex.Match(description);
                        if (boolean.Success)
                        {
                            return(new PythonAppConfigBoolValue(boolean.Groups[1].Value, boolean.Groups[2].Value));
                        }

                        var range = RangeRegex.Match(description);
                        if (range.Success)
                        {
                            return(new PythonAppConfigRangeValue(FlexibleParser.TryParseDouble(range.Groups[1].Value) ?? 0d,
                                                                 FlexibleParser.TryParseDouble(range.Groups[3].Value) ?? 100d, range.Groups[2].Success ? range.Groups[2].Value : null));
                        }

                        var file = FileRegex.Match(description);
                        if (file.Success)
                        {
                            return(new PythonAppConfigFileValue(file.Groups[1].Success, file.Groups[2].Success ? file.Groups[2].Value : null));
                        }

                        if (description.IndexOf(',') != -1)
                        {
                            var options = OptionsRegex.Matches(description).Cast <Match>()
                                          .Select(x => (x.Groups[1].Success ? x.Groups[1].Value : x.Groups[2].Value).Trim()).ToArray();
                            if (options.Length > 0)
                            {
                                return(new PythonAppConfigOptionsValue(options.Select(x => {
                                    var m = OptionValueRegex.Match(x);
                                    return m.Success ? new SettingEntry(m.Groups[2].Value.TrimStart(), m.Groups[1].Value.TrimEnd()) : new SettingEntry(x, x);
                                }).ToArray()));
                            }
                        }
                    }
                }
            }

            switch (value)
            {
            case "True":
            case "False":
                return(new PythonAppConfigBoolValue());

            case "true":
            case "false":
                return(new PythonAppConfigBoolValue("true", "false"));

            case "TRUE":
            case "FALSE":
                return(new PythonAppConfigBoolValue("TRUE", "FALSE"));

            case "On":
            case "Off":
                return(new PythonAppConfigBoolValue("On", "Off"));

            case "on":
            case "off":
                return(new PythonAppConfigBoolValue("on", "off"));

            case "ON":
            case "OFF":
                return(new PythonAppConfigBoolValue("ON", "OFF"));
            }

            return(new PythonAppConfigValue());
        }