示例#1
0
        private static async Task <ArgumentHandleResult> ProcessRaceOnlineJoin(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");
            }

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

            await JoinInvitation(ip, httpPort.Value, password);

            return(ArgumentHandleResult.Successful);
        }
示例#2
0
        private static ITestEntry CreateNumericTestEntry(Operator op, string key, string value)
        {
            if (value.IndexOf(':') != -1)
            {
                return(CreateTimeSpanTestEntry(op, value));
            }

            var point = value.IndexOf('.');

            if (point != -1 && value.IndexOf('.', point + 1) != -1 || value.IndexOf('/') != -1 || value.IndexOf('-') > 0)
            {
                return(CreateDateTimeTestEntry(op, value));
            }

            if (DistanceTestEntry.IsDistanceKey(key) || DistanceTestEntry.IsDistanceValue(value))
            {
                double num;
                return(DistanceTestEntry.ToMeters(value, out num) ? new DistanceTestEntry(op, num) :
                       (ITestEntry) new ConstTestEntry(false));
            }

            if (point != -1 || value.IndexOf(',') != -1)
            {
                double num;
                return(FlexibleParser.TryParseDouble(value, out num) ? new NumberTestEntry(op, num) :
                       (ITestEntry) new ConstTestEntry(false));
            }
            else
            {
                int num;
                return(FlexibleParser.TryParseInt(value, out num) ? new IntTestEntry(op, num) :
                       (ITestEntry) new ConstTestEntry(false));
            }
        }
        private bool TryToLoad()
        {
            _skipSaving = true;

            try {
                IniFile iniFile;
                try {
                    iniFile = new IniFile(_filename);
                } catch (Exception e) {
                    NonfatalError.Notify("Can’t load Kunos career progress", e);
                    return(false);
                }

                Current = iniFile["CAREER"].GetNonEmpty("CURRENT");
                AiLevel = iniFile["CAREER"].GetDouble("AI_LEVEL", 95d);
                Entries = iniFile.Where(x => x.Key != "CHAMPS").ToDictionary(
                    x => x.Key.ToLowerInvariant(),
                    x => new UserChampionshipProgressEntry(
                        x.Value.GetInt("EVENT", 0),
                        x.Value.Select(y => new {
                    Key = y.Key.StartsWith(@"EVENT") ? FlexibleParser.TryParseInt(y.Key.Substring(5)) : null as int?,
                    y.Value
                }).Where(y => y.Key.HasValue).ToDictionary(y => y.Key.Value, y => FlexibleParser.ParseInt(y.Value, 0)),
                        x.Value.GetIntNullable("POINTS"),
                        x.Value.Select(y => new {
                    Key = y.Key.StartsWith(@"AI") ? FlexibleParser.TryParseInt(y.Key.Substring(2)) - 1 : null as int?,
                    y.Value
                }).Where(y => y.Key.HasValue).ToDictionary(y => y.Key.Value, y => FlexibleParser.ParseInt(y.Value, 0))));

                return(true);
            } finally {
                _skipSaving = false;
            }
        }
示例#4
0
        private static string CleanUp(string name, [CanBeNull] string oldName, out int?extPort)
        {
            var specialIndex = name.IndexOf(ExtendedSeparator, StringComparison.InvariantCulture);

            if (specialIndex != -1)
            {
                extPort = FlexibleParser.TryParseInt(name.Substring(specialIndex + ExtendedSeparator.Length));
                name    = name.Substring(0, specialIndex).Trim();
            }
            else
            {
                extPort = null;
                name    = name.Trim();
            }

            name = SpacesCollapseRegex.Replace(name, " ");
            if (SettingsHolder.Online.FixNames)
            {
                name = SortingCheatsRegex.Replace(name, "");
            }
            else if (oldName != null && SimpleCleanUpRegex.IsMatch(name) && !SimpleCleanUpRegex.IsMatch(oldName))
            {
                name = SimpleCleanUpRegex.Replace(name, "");
            }
            return(name);
        }
示例#5
0
        public IEnumerable <LapTimeEntry> Import(string sourceName)
        {
            var file = new FileInfo(Path.Combine(_ov1Directory, "userdata", "best_lap.ini"));

            if (!file.Exists)
            {
                yield break;
            }

            var ini  = new IniFile(file.FullName);
            var date = file.CreationTime;

            foreach (var section in ini)
            {
                var trackLayoutId = _fixer.FixTrackId(section.Key);
                foreach (var pair in section.Value)
                {
                    var time = TimeSpan.FromMilliseconds(FlexibleParser.TryParseInt(pair.Value) ?? 0);
                    if (time.TotalSeconds < 1d)
                    {
                        continue;
                    }
                    yield return(new LapTimeEntry(sourceName, pair.Key.ToLowerInvariant(), trackLayoutId,
                                                  date, time));
                }
            }
        }
示例#6
0
        protected override void LoadFromIni()
        {
            if (Devices.Count == 0)
            {
                // RescanDevices();
            }

            InputMethod = Ini["HEADER"].GetEntry("INPUT_METHOD", InputMethods);
            CombineWithKeyboardInput = Ini["ADVANCED"].GetBool("COMBINE_WITH_KEYBOARD_CONTROL", false);
            WheelUseHShifter         = Ini["SHIFTER"].GetBool("ACTIVE", false);
            DebouncingInterval       = Ini["STEER"].GetInt("DEBOUNCING_MS", 50);

            foreach (var device in Devices.OfType <IDirectInputDevice>().Union(_placeholderDevices))
            {
                device.OriginalIniIds.Clear();
            }

            var section = Ini["CONTROLLERS"];
            var devices = section.Keys.Where(x => x.StartsWith(@"CON")).Select(x => new {
                IniId = FlexibleParser.TryParseInt(x.Substring(3)),
                Name  = section.GetNonEmpty(x)
            }).TakeWhile(x => x.Name != null && x.IniId.HasValue).Select(x => {
                var id = section.GetNonEmpty($"PGUID{x.IniId}");
                if (id != null)
                {
                    ProductGuids[x.Name] = id;
                }

                var device = Devices.FirstOrDefault(y => y.Device.InstanceName == x.Name) ?? Devices.GetByIdOrDefault(id);
                if (device != null)
                {
                    device.OriginalIniIds.Add(x.IniId.Value);
                    return(device);
                }

                return((IDirectInputDevice)GetPlaceholderDevice(id, x.Name, x.IniId.Value));
            }).ToList();

            foreach (var entry in Entries)
            {
                entry.Load(Ini, devices);
            }

            LoadFfbFromIni(Ini);

            section = Ini["KEYBOARD"];
            KeyboardSteeringSpeed      = section.GetDouble("STEERING_SPEED", 1.75);
            KeyboardOppositeLockSpeed  = section.GetDouble("STEERING_OPPOSITE_DIRECTION_SPEED", 2.5);
            KeyboardReturnRate         = section.GetDouble("STEER_RESET_SPEED", 1.8);
            KeyboardMouseSteering      = section.GetBool("MOUSE_STEER", false);
            KeyboardMouseButtons       = section.GetBool("MOUSE_ACCELERATOR_BRAKE", false);
            KeyboardMouseSteeringSpeed = section.GetDouble("MOUSE_SPEED", 0.1);

            section = Ini["__LAUNCHER_CM"];
            var name = section.GetNonEmpty("PRESET_NAME");

            CurrentPresetFilename = name == null ? null : Path.Combine(PresetsDirectory, name);
            CurrentPresetChanged  = CurrentPresetName != null && section.GetBool("PRESET_CHANGED", true);
        }
示例#7
0
 public bool Test(string value)
 {
     if (value == null)
     {
         return(false);
     }
     return(FlexibleParser.TryParseInt(value, out var val) && Test(val));
 }
示例#8
0
        public async Task UpdateProgress(IProgress <string> progress, CancellationToken cancellation)
        {
            if (SteamIdHelper.Instance.Value == null)
            {
                throw new InformativeException("Can’t get challenges progress", "Steam ID is missing.");
            }

            progress.Report("Finishing preparing…");
            await EnsureLoadedAsync();

            if (cancellation.IsCancellationRequested)
            {
                return;
            }

            progress.Report("Loading stats…");
            string[] achievments;
            try {
                achievments = await Task.Run(() => SteamWebProvider.GetAchievments(CommonAcConsts.AppId, SteamIdHelper.Instance.Value), cancellation);

                if (cancellation.IsCancellationRequested)
                {
                    return;
                }
            } catch (WebException e)
                when(e.Status == WebExceptionStatus.ProtocolError && (e.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.InternalServerError)
                {
                    throw new InformativeException("Can’t get challenges progress because of internal server error (500)", "Make sure Steam account isn’t private.");
                }

            foreach (var eventObject in LoadedOnly)
            {
                eventObject.TakenPlace = 5;
            }

            foreach (var achievment in achievments.Where(x => x.StartsWith(@"SPECIAL_EVENT_")))
            {
                var id    = achievment.Substring(0, achievment.Length - 2);
                var place = FlexibleParser.TryParseInt(achievment.Substring(achievment.Length - 1));

                var eventObject = GetById(id);
                if (eventObject == null || !place.HasValue)
                {
                    continue;
                }

                eventObject.TakenPlace = Math.Min(eventObject.TakenPlace, (eventObject.ConditionType == null ? 4 : 3) - place.Value);
            }
        }
示例#9
0
        private static string CleanUp(string name, [CanBeNull] string oldName, out int?extPort, out string detailsId)
        {
            var originalName = name;

            name = ServerDetailsUtils.ExtractDetailsId(name, out detailsId);

            var specialIndex = name.IndexOf(ExtendedSeparator, StringComparison.InvariantCulture);

            if (specialIndex != -1)
            {
                extPort = FlexibleParser.TryParseInt(name.Substring(specialIndex + ExtendedSeparator.Length));
                name    = name.Substring(0, specialIndex);
            }
            else
            {
                extPort = null;
            }

            name = InvisibleCleanUp(name.Trim());
            name = SpacesCollapseRegex.Replace(name, " ");

            var fixMode = SettingsHolder.Online.FixNamesMode.IntValue ?? 0;

            if (fixMode != 0)
            {
                name = SortingFix2Regex.Replace(name, "");

                if (fixMode == 2)
                {
                    var v = SortingFix1Regex.Replace(name, " ");
                    if (v != name)
                    {
                        name = SpacesCollapseRegex.Replace(v, " ").Trim();
                    }
                }
            }
            else if (oldName != null && SimpleCleanUpRegex.IsMatch(name) && !SimpleCleanUpRegex.IsMatch(oldName))
            {
                name = SimpleCleanUpRegex.Replace(name, "");
            }

            return(string.IsNullOrWhiteSpace(name) ? originalName : name);
        }
示例#10
0
        public static object Deserialize([CanBeNull] string serialized)
        {
            if (serialized == null)
            {
                return(RandomWeather);
            }

            if (serialized.StartsWith(@"*"))
            {
                try {
                    return(new WeatherTypeWrapped((WeatherType)(FlexibleParser.TryParseInt(serialized.Substring(1)) ?? 0)));
                } catch (Exception e) {
                    Logging.Error(e);
                    return(null);
                }
            }

            return(WeatherManager.Instance.GetById(serialized));
        }
示例#11
0
        private bool TryToLoad()
        {
            _skipSaving = true;

            try {
                IniFile iniFile;
                try {
                    iniFile = new IniFile(_filename);
                } catch (Exception e) {
                    NonfatalError.Notify("Can’t load Kunos career progress", e);
                    return(false);
                }

                Completed     = iniFile["CAREER"].GetStrings("COMPLETE").Select(x => x.ToLowerInvariant()).ToArray();
                CurrentSeries = iniFile["CAREER"].GetNonEmpty("CURRENTSERIES");
                AiLevel       = iniFile["CAREER"].GetDouble("AI_LEVEL", 95d);
                IsNew         = iniFile["CAREER"].GetInt("INTRO", 0) != 2;
                Entries       = iniFile.Where(x => x.Key.StartsWith(@"SERIES")).ToDictionary(
                    x => x.Key.ToLowerInvariant(),
                    x => new KunosCareerProgressEntry(
                        x.Value.GetInt("EVENT", 0),
                        x.Value.Select(y => new {
                    Key = y.Key.StartsWith(@"EVENT") ? FlexibleParser.TryParseInt(y.Key.Substring(5)) : null as int?,
                    y.Value
                }).Where(y => y.Key.HasValue).ToDictionary(y => y.Key.Value, y => FlexibleParser.ParseInt(y.Value, 0)),
                        x.Value.GetIntNullable("POINTS"),
                        x.Value.Select(y => new {
                    Key = y.Key.StartsWith(@"AI") ? FlexibleParser.TryParseInt(y.Key.Substring(2)) - 1 : null as int?,
                    y.Value
                }).Where(y => y.Key.HasValue).ToDictionary(y => y.Key.Value, y => FlexibleParser.ParseInt(y.Value, 0)),
                        x.Value.GetLong("LASTSELECTED", 0)));

                return(true);
            } finally {
                _skipSaving = false;
            }
        }
示例#12
0
 public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
 {
     return(new object[] { FlexibleParser.TryParseInt(value?.ToString()) ?? 0, 0 });
 }
示例#13
0
            public void SetParam(string key, string value)
            {
                Sync(() => {
                    switch (key)
                    {
                    case "REMOTE/REQUESTED_CAR":
                        _model.CarId = value;
                        break;

                    case "CAR_0/SKIN":
                        _model.CarSkinId = value;
                        break;

                    case "REMOTE/SERVER_IP":
                        if (value != _model.Server?.Ip)
                        {
                            _model.Server = new ServerInformation(value, _model.Server?.Port, _model.Server?.PortHttp, _model.Server?.Password,
                                                                  _model.Server?.DisplayName);
                        }
                        break;

                    case "REMOTE/SERVER_PORT":
                        var port = FlexibleParser.TryParseInt(value);
                        if (port != _model.Server?.Port)
                        {
                            _model.Server = new ServerInformation(_model.Server?.Ip, port, _model.Server?.PortHttp, _model.Server?.Password,
                                                                  _model.Server?.DisplayName);
                        }
                        break;

                    case "REMOTE/SERVER_HTTP_PORT":
                        var portHttp = FlexibleParser.TryParseInt(value);
                        if (portHttp != _model.Server?.PortHttp)
                        {
                            _model.Server = new ServerInformation(_model.Server?.Ip, _model.Server?.Port, portHttp,
                                                                  _model.Server?.Password, _model.Server?.DisplayName);
                        }
                        break;

                    case "REMOTE/PASSWORD":
                        if (value != _model.Server?.Password)
                        {
                            _model.Server = new ServerInformation(_model.Server?.Ip, _model.Server?.Port, _model.Server?.PortHttp, value,
                                                                  _model.Server?.DisplayName);
                        }
                        break;

                    case "REMOTE/SERVER_NAME":
                        if (value != _model.Server?.DisplayName)
                        {
                            _model.Server = new ServerInformation(_model.Server?.Ip, _model.Server?.Port, _model.Server?.PortHttp, _model.Server?.Password,
                                                                  value);
                        }
                        break;

                    case "REMOTE/NAME":
                        Logging.Debug(value);
                        if (value != _model.Player?.DisplayName)
                        {
                            _model.Player = new PlayerInformation(value, _model.Player?.Team, _model.Player?.Nationality);
                        }
                        break;

                    case "REMOTE/TEAM":
                        if (value != _model.Player?.Team)
                        {
                            _model.Player = new PlayerInformation(_model.Player?.DisplayName, value, _model.Player?.Nationality);
                        }
                        break;

                    case "CAR_0/NATIONALITY":
                        if (value != _model.Player?.Nationality)
                        {
                            _model.Player = new PlayerInformation(_model.Player?.DisplayName, _model.Player?.Team, value);
                        }
                        break;
                    }
                });
            }
示例#14
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);
        }
示例#15
0
        protected override void LoadData(IniFile ini)
        {
            Name        = ini["SERIES"].GetPossiblyEmpty("NAME");
            Code        = ini["SERIES"].GetPossiblyEmpty("CODE");
            Description = AcStringValues.DecodeDescription(ini["SERIES"].GetPossiblyEmpty("DESCRIPTION"));

            PointsForPlace          = ini["SERIES"].GetPossiblyEmpty("POINTS")?.Split(',').Select(x => FlexibleParser.TryParseInt(x)).OfType <int>().ToArray();
            ChampionshipPointsGoal  = ini["GOALS"].GetIntNullable("POINTS") ?? 0;
            ChampionshipRankingGoal = ini["GOALS"].GetIntNullable("RANKING") ?? 0;
            ThirdPlacesGoal         = ini["GOALS"].GetIntNullable("TIER1") ?? 0;
            SecondPlacesGoal        = ini["GOALS"].GetIntNullable("TIER2") ?? 0;
            FirstPlacesGoal         = ini["GOALS"].GetIntNullable("TIER3") ?? 0;
            Type = ChampionshipPointsGoal == 0 && ChampionshipRankingGoal == 0 || PointsForPlace?.Sum() == 0
                    ? KunosCareerObjectType.SingleEvents : KunosCareerObjectType.Championship;

            RequiredSeries    = ini["SERIES"].GetStrings("REQUIRES").ToArray();
            RequiredAnySeries = ini["SERIES"].GetBool("REQUIRESANY", false);

            ChampionshipPointsPerPlace = ini["SERIES"].GetStrings("POINTS").Select(x => FlexibleParser.TryParseInt(x)).OfType <int>().ToArray();

            if (Type == KunosCareerObjectType.Championship)
            {
                LoadOpponents();
            }
        }
示例#16
0
        private static async Task <ArgumentHandleResult> ProcessRaceOnline(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);
        }
示例#17
0
        internal string ProcessText(string text, double delta)
        {
            var mode     = GetMode(this);
            var minValue = GetMinimum(this);
            var maxValue = GetMaximum(this);

            switch (mode)
            {
            case SpecialMode.Number: {
                double value;
                if (!FlexibleParser.TryParseDouble(text, out value))
                {
                    return(null);
                }

                if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
                {
                    delta *= 0.1;
                }

                if ((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift)
                {
                    delta *= 10.0;
                }

                if ((Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt)
                {
                    delta *= 2.0;
                }

                value += delta;
                value  = Math.Max(Math.Min(value, maxValue), minValue);
                return(FlexibleParser.ReplaceDouble(text, value));
            }

            case SpecialMode.Integer:
#pragma warning disable 612
            case SpecialMode.Positive: {
#pragma warning restore 612
                int value;
                if (!FlexibleParser.TryParseInt(text, out value))
                {
                    return(null);
                }

                if ((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift)
                {
                    delta *= 10.0;
                }

                if ((Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt)
                {
                    delta *= 2.0;
                }

                value = (int)Math.Max(Math.Min((int)(value + delta), maxValue), minValue);
#pragma warning disable 612
                if (mode == SpecialMode.Positive && value < 1)
                {
#pragma warning restore 612
                    value = 1;
                }
                return(FlexibleParser.ReplaceDouble(text, value));
            }

            case SpecialMode.IntegerOrLabel:
#pragma warning disable 612
            case SpecialMode.IntegerOrMinusOneLabel:
            case SpecialMode.IntegerOrZeroLabel: {
#pragma warning restore 612
                int value;
                var skip = !FlexibleParser.TryParseInt(text, out value);

                if (skip)
                {
                    value = GetLabelValue();
                }

                if ((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift)
                {
                    delta *= 10.0;
                }

                if ((Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt)
                {
                    delta *= 2.0;
                }

                value = (int)Math.Max(Math.Min((int)(value + delta), maxValue), minValue);

                var label = GetModeLabel(this);
                if (value == GetLabelValue() && label != null)
                {
                    return(label);
                }

                return(skip ? value.ToString(CultureInfo.InvariantCulture) : FlexibleParser.ReplaceDouble(text, value));
            }

            case SpecialMode.Time: {
                var splitted = text.Split(':');
                int totalSeconds;

                switch (splitted.Length)
                {
                case 2: {
                    int hours, minutes;
                    if (!FlexibleParser.TryParseInt(splitted[0], out hours) || !FlexibleParser.TryParseInt(splitted[1], out minutes))
                    {
                        return(null);
                    }
                    totalSeconds = (splitted[0].StartsWith(@"-") ? -1 : 1) * (Math.Abs(hours) * 60 + Math.Abs(minutes)) * 60;
                    break;
                }

                case 3: {
                    int hours, minutes, seconds;
                    if (!FlexibleParser.TryParseInt(splitted[0], out hours) || !FlexibleParser.TryParseInt(splitted[1], out minutes) ||
                        !FlexibleParser.TryParseInt(splitted[2], out seconds))
                    {
                        return(null);
                    }
                    totalSeconds = (splitted[0].StartsWith(@"-") ? -1 : 1) * (Math.Abs(hours) * 60 + Math.Abs(minutes)) * 60 + Math.Abs(seconds);
                    break;
                }

                default:
                    return(null);
                }

                if (!Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
                {
                    delta *= 60;
                }

                if (Keyboard.Modifiers.HasFlag(ModifierKeys.Shift))
                {
                    delta *= 60;
                }

                if (Keyboard.Modifiers.HasFlag(ModifierKeys.Alt))
                {
                    delta *= 15;
                }

                if (double.IsNegativeInfinity(minValue))
                {
                    minValue = 0d;
                }

                totalSeconds += (int)delta;
                totalSeconds  = (int)Math.Max(Math.Min(totalSeconds, maxValue), minValue);

                var t = Math.Abs(totalSeconds);
                return(splitted.Length == 2
                            ? $@"{(totalSeconds < 0 ? @"-" : "")}{t / 3600:D2}:{t / 60 % 60:D2}"
                            : $@"{(totalSeconds < 0 ? @"-" : "")}{t / 3600:D2}:{t / 60 % 60:D2}:{t % 60:D2}");
            }

            case SpecialMode.Version: {
                var splitted = text.Split('.');
                var index    = splitted.Length - 1;

                if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
                {
                    index--;
                }

                if ((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift)
                {
                    index--;
                }

                if ((Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt)
                {
                    index--;
                }

                if (index < 0)
                {
                    index = 0;
                }

                int value;
                if (FlexibleParser.TryParseInt(splitted[index], out value))
                {
                    splitted[index] = FlexibleParser.ReplaceDouble(splitted[index], value + delta);
                }

                return(string.Join(@".", splitted));
            }

            default:
                throw new ArgumentOutOfRangeException(nameof(mode), mode, null);
            }
        }
示例#18
0
 public int GetInt([NotNull, LocalizationRequired(false)] string key, int defaultValue)
 {
     return(FlexibleParser.TryParseInt(GetPossiblyEmpty(key)) ?? defaultValue);
 }
示例#19
0
 public int?GetIntNullable([NotNull, LocalizationRequired(false)] string key)
 {
     return(FlexibleParser.TryParseInt(GetPossiblyEmpty(key)));
 }
示例#20
0
 internal static SelectRating Deserialize(string data)
 {
     return(data == @"-" ? new SelectRating(null) : new SelectRating(FlexibleParser.TryParseInt(data)));
 }
示例#21
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)));
 }