Exemple #1
0
        public void Load()
        {
            // Create new graphics control
            _mapGraphics = new Map2Graphics(_mapGui.GLControl);
            _mapGraphics.Load();

            _isLoaded = true;

            // Set the default map
            ChangeCurrentMap(Config.MapAssociations.DefaultMap);

            // Add Mario's map object
            _mapGraphics.AddMapObject(_marioMapObj);
            _mapGraphics.AddMapObject(_holpMapObj);
            _mapGraphics.AddMapObject(_intendedNextPositionMapObj);
            _mapGraphics.AddMapObject(_pointMapObj);
            _mapGraphics.AddMapObject(_cameraMapObj);
            _mapGraphics.AddMapObject(_floorTriangleMapObj);
            _mapGraphics.AddMapObject(_ceilingTriangleMapObj);

            _cogFloorTris.ForEach(tri => _mapGraphics.AddMapObject(tri));
            _cog2FloorTris.ForEach(tri => _mapGraphics.AddMapObject(tri));
            _cogWallTris.ForEach(tri => _mapGraphics.AddMapObject(tri));

            foreach (List <TriangleMap2Object> floorTris in _triObjectFloors)
            {
                foreach (TriangleMap2Object floorTri in floorTris)
                {
                    _mapGraphics.AddMapObject(floorTri);
                }
            }

            foreach (List <TriangleMap2Object> wallTris in _triObjectWalls)
            {
                foreach (TriangleMap2Object wallTri in wallTris)
                {
                    _mapGraphics.AddMapObject(wallTri);
                }
            }

            //----- Register events ------
            // Set image
            _mapGui.MapIconSizeTrackbar.ValueChanged += (sender, e) => _mapGraphics.IconSize = _mapGui.MapIconSizeTrackbar.Value;

            _mapGui.MapBoundsUpButton.Click        += (sender, e) => ChangeMapPosition(0, 1);
            _mapGui.MapBoundsDownButton.Click      += (sender, e) => ChangeMapPosition(0, -1);
            _mapGui.MapBoundsLeftButton.Click      += (sender, e) => ChangeMapPosition(-1, 0);
            _mapGui.MapBoundsRightButton.Click     += (sender, e) => ChangeMapPosition(1, 0);
            _mapGui.MapBoundsUpLeftButton.Click    += (sender, e) => ChangeMapPosition(-1, 1);
            _mapGui.MapBoundsUpRightButton.Click   += (sender, e) => ChangeMapPosition(1, 1);
            _mapGui.MapBoundsDownLeftButton.Click  += (sender, e) => ChangeMapPosition(-1, -1);
            _mapGui.MapBoundsDownRightButton.Click += (sender, e) => ChangeMapPosition(1, -1);

            _mapGui.MapBoundsZoomInButton.Click  += (sender, e) => ChangeMapZoom(1);
            _mapGui.MapBoundsZoomOutButton.Click += (sender, e) => ChangeMapZoom(-1);

            _mapGui.MapArtificialMarioYLabelTextBox.AddEnterAction(() =>
                                                                   _artificialMarioY = ParsingUtilities.ParseFloatNullable(
                                                                       _mapGui.MapArtificialMarioYLabelTextBox.Text));
        }
Exemple #2
0
 private void textBoxOpacity_EnterAction()
 {
     SetOpacity(ParsingUtilities.ParseFloatNullable(textBoxOpacity.Text), false);
 }
Exemple #3
0
 /// <summary>
 /// Converts the string representation of a MIDI time span to its <see cref="MidiTimeSpan"/>
 /// equivalent.
 /// </summary>
 /// <param name="input">A string containing a time span to convert.</param>
 /// <returns>A <see cref="MidiTimeSpan"/> equivalent to the time span contained in
 /// <paramref name="input"/>.</returns>
 /// <exception cref="ArgumentException"><paramref name="input"/> is <c>null</c> or contains white-spaces only.</exception>
 /// <exception cref="FormatException"><paramref name="input"/> has invalid format.</exception>
 public static MidiTimeSpan Parse(string input)
 {
     return(ParsingUtilities.Parse <MidiTimeSpan>(input, MidiTimeSpanParser.TryParse));
 }
 private ushort?GetCurrentPointerOffset()
 {
     return(ParsingUtilities.ParseUShortNullable(
                ParsingUtilities.ParseHexNullable(textBoxPointerOffsetValue.Text)));
 }
Exemple #5
0
        public static byte[] GetBytesFromString(this WatchVariable watchVar, uint offset, string value)
        {
            // Get dataBytes
            var address   = watchVar.HasAdditiveOffset ? offset + watchVar.Address : watchVar.Address;
            var dataBytes = new byte[8];

            Config.Stream.ReadRamLittleEndian(new UIntPtr(address), watchVar.ByteCount, watchVar.UseAbsoluteAddressing).CopyTo(dataBytes, 0);
            UInt64 oldValue = BitConverter.ToUInt64(dataBytes, 0);
            UInt64 newValue;


            // Handle object values
            uint?objectAddress;

            if (watchVar.IsObject && (objectAddress = ManagerContext.Current.ObjectSlotManager.GetSlotAddressFromName(value)).HasValue)
            {
                newValue = objectAddress.Value;
            }
            else
            // Handle hex variable
            if (ParsingUtilities.IsHex(value))
            {
                if (!ParsingUtilities.TryParseExtHex(value, out newValue))
                {
                    return(null);
                }
            }
            // Handle floats
            else if (watchVar.Type == typeof(float))
            {
                float newFloatValue;
                if (!float.TryParse(value, out newFloatValue))
                {
                    return(null);
                }

                // Get bytes
                newValue = BitConverter.ToUInt32(BitConverter.GetBytes(newFloatValue), 0);
            }
            else if (watchVar.Type == typeof(double))
            {
                double newFloatValue;
                if (double.TryParse(value, out newFloatValue))
                {
                    return(null);
                }

                // Get bytes
                newValue = BitConverter.ToUInt64(BitConverter.GetBytes(newFloatValue), 0);
            }
            else if (watchVar.Type == typeof(UInt64))
            {
                if (!UInt64.TryParse(value, out newValue))
                {
                    Int64 newValueInt;
                    if (!Int64.TryParse(value, out newValueInt))
                    {
                        return(null);
                    }

                    newValue = (UInt64)newValueInt;
                }
            }
            else
            {
                Int64 tempInt;
                if (!Int64.TryParse(value, out tempInt))
                {
                    return(null);
                }
                newValue = (UInt64)tempInt;
            }

            // Apply mask
            if (watchVar.Mask.HasValue)
            {
                newValue = (newValue & watchVar.Mask.Value) | ((~watchVar.Mask.Value) & oldValue);
            }

            var writeBytes = new byte[watchVar.ByteCount];
            var valueBytes = BitConverter.GetBytes(newValue);

            Array.Copy(valueBytes, 0, writeBytes, 0, watchVar.ByteCount);

            return(writeBytes);
        }
Exemple #6
0
        /// <summary>
        /// Parses the specified record text into a clearing data record if possible.
        /// </summary>
        /// <param name="record">
        /// The record text to parse into a clearing data record.
        /// </param>
        /// <param name="recordNumber">
        /// The number of the record of this type from the extract file being parsed.
        /// </param>
        /// <returns>
        /// * The ClearingData object if successful.
        /// * Else returns null.
        /// </returns>
        internal ClearingData Parse(string record,
                                    int recordNumber)
        {
            ClearingData result = new ClearingData();

            int      recordPos    = 0;
            bool     recordValid  = true;
            string   stringField  = null;
            decimal  decimalField = Decimal.MinValue;
            DateTime dateField    = DateTime.MinValue;

            ParsingUtilities parsingUtilities = new ParsingUtilities("Clearing File Data Record", recordNumber, FileName, ClearingConstants.ShortTimeFieldLength, Log);

            // RecordType
            recordValid = parsingUtilities.VerifyString(record, ref recordPos, "Record Type", RecordType, ClearingConstants.RecordTypeLength, recordValid);

            // Transaction sequence number.
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField, ClearingConstants.TransactionSequenceNumberLength, recordValid);
            result.TransactionSequenceNumber = stringField;

            // Bank account number.
            recordValid = parsingUtilities.VerifyString(record, ref recordPos, "Bank Account Number", EmptyBankAccountNumber, ClearingConstants.BankAccountNumberLength,
                                                        false, recordValid);

            // Transaction amount.
            recordValid = parsingUtilities.PopulateDecimal(record, ref recordPos, "Transaction Amount", out decimalField, ClearingConstants.TransactionAmountLength,
                                                           recordValid);
            result.TransactionAmount = decimalField;

            // Transaction date. Save this for later combination with transaction time.
            recordValid = parsingUtilities.PopulateDateTime(record, ref recordPos, "Transaction Date", out dateField, false, false, recordValid);
            DateTime transactionDate = dateField;

            // Merchant DBA name.
            recordValid            = parsingUtilities.PopulateString(record, ref recordPos, out stringField, ClearingConstants.MerchantDbaNameLength, recordValid);
            result.MerchantDbaName = stringField;

            // Merchant ID.
            recordValid       = parsingUtilities.PopulateString(record, ref recordPos, out stringField, ClearingConstants.MerchantIdLength, recordValid);
            result.MerchantId = stringField;

            // Location ID.
            recordValid       = parsingUtilities.PopulateString(record, ref recordPos, out stringField, ClearingConstants.LocationIdLength, recordValid);
            result.LocationId = stringField;

            // Issuer ICA.
            recordValid      = parsingUtilities.PopulateString(record, ref recordPos, out stringField, ClearingConstants.IssuerIcaLength, recordValid);
            result.IssuerIca = stringField;

            // Transaction time.
            recordValid            = parsingUtilities.PopulateTimeForExistingDate(record, ref recordPos, "Transaction Time", ref transactionDate, recordValid);
            result.TransactionDate = transactionDate;

            // Bank Net ref number.
            recordValid             = parsingUtilities.PopulateString(record, ref recordPos, out stringField, ClearingConstants.BankNetRefNumberLength, recordValid);
            result.BankNetRefNumber = stringField;

            // Bank customer number.
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField, ClearingConstants.BankCustomerNumberLength, recordValid);
            result.BankCustomerNumber = stringField;

            // Aggregate merchant ID.
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField, ClearingConstants.AggregateMerchantIdLength, recordValid);
            result.AggregateMerchantId = stringField;

            // If the record is not valid, return a null value.
            if (recordValid == false)
            {
                result = null;
            }

            return(result);
        }
Exemple #7
0
 /// <summary>
 /// Converts the string representation of a musical chord to its <see cref="Chord"/> equivalent.
 /// </summary>
 /// <param name="input">A string containing a chord to convert.</param>
 /// <returns>A <see cref="Chord"/> equivalent to the musical chord contained in <paramref name="input"/>.</returns>
 /// <exception cref="ArgumentException"><paramref name="input"/> is null or contains white-spaces only.</exception>
 /// <exception cref="FormatException"><paramref name="input"/> has invalid format.</exception>
 public static Chord Parse(string input)
 {
     return(ParsingUtilities.Parse <Chord>(input, ChordParser.TryParse));
 }
Exemple #8
0
 /// <summary>
 /// Converts the string representation of a musical interval to its <see cref="Scale"/> equivalent.
 /// </summary>
 /// <param name="input">A string containing an interval to convert.</param>
 /// <returns>A <see cref="Scale"/> equivalent to the musical interval contained in <paramref name="input"/>.</returns>
 /// <exception cref="ArgumentException"><paramref name="input"/> is null or contains white-spaces only.</exception>
 /// <exception cref="FormatException"><paramref name="input"/> has invalid format.</exception>
 public static Interval Parse(string input)
 {
     return(ParsingUtilities.Parse <Interval>(input, IntervalParser.TryParse));
 }
        /// <summary>
        /// Parses the specified record text into a redemption detail object if possible.
        /// </summary>
        /// <param name="record">
        /// The record text to parse into a redemption detail object.
        /// </param>
        /// <param name="recordNumber">
        /// The number of the record of this type from the extract file being parsed.
        /// </param>
        /// <returns>
        /// * The RedemptionDetail object if successful.
        /// * Else returns null.
        /// </returns>
        internal RedemptionDetail Parse(string record,
                                        int recordNumber)
        {
            RedemptionDetail result = new RedemptionDetail();

            RecordNumber = recordNumber;

            int      recordPos    = 0;
            bool     recordValid  = true;
            string   stringField  = null;
            DateTime dateField    = DateTime.MinValue;
            decimal  decimalField = Decimal.MinValue;

            ParsingUtilities parsingUtilities = new ParsingUtilities(RecordTypeDescriptor, RecordNumber, FileName, ExtractConstants.TimeFieldLength, Log);

            // RecordType
            recordValid = parsingUtilities.VerifyString(record, ref recordPos, "Record Type", RecordType,
                                                        ExtractConstants.RecordTypeLength, recordValid);

            // ProviderId
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField,
                                                          ExtractConstants.ProviderIdLength, recordValid);
            result.ProviderId = stringField;

            // ProviderLevelNumber
            recordValid = parsingUtilities.VerifyString(record, ref recordPos, "Hierarchy Level No.",
                                                        ExtractConstants.ProviderLevelNumber,
                                                        ExtractConstants.ProviderLevelNumberLength, recordValid);

            // TransactionId
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField,
                                                          ExtractConstants.TransactionIdLength, recordValid);
            result.TransactionId = stringField;

            // TransactionType
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField,
                                                          ExtractConstants.TransactionTypeLength, recordValid);
            TransactionType transactionType;

            recordValid            = DetermineTransactionType(stringField, "Transaction Type", out transactionType, recordValid);
            result.TransactionType = transactionType;

            // TransactionDateTime
            recordValid = parsingUtilities.PopulateDateTime(record, ref recordPos, "Transaction Date\" and \"Transaction Time",
                                                            out dateField, true, true, recordValid);
            result.TransactionDateTime = dateField;

            // LocalDateTime
            recordValid = parsingUtilities.PopulateDateTime(record, ref recordPos, "Local Date\" and \"Local Time",
                                                            out dateField, true, true, recordValid);
            result.LocalDateTime = dateField;

            // PublisherName
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField,
                                                          ExtractConstants.PublisherNameLength, recordValid);
            result.PublisherName = stringField;

            // PublisherId
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField,
                                                          ExtractConstants.PublisherIdLength, recordValid);
            result.PublisherId = stringField;

            // ConsumerId
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField,
                                                          ExtractConstants.ConsumerIdLength, recordValid);
            result.ConsumerId = stringField;

            // CardSuffix
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField,
                                                          ExtractConstants.CardSuffixLength, recordValid);
            result.CardSuffix = stringField;

            // OfferId
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField, ExtractConstants.OfferIdLength,
                                                          recordValid);
            result.OfferId = stringField;

            // OfferType
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField,
                                                          ExtractConstants.OfferTypeLength, recordValid);
            OfferType offerType;

            recordValid      = DetermineOfferType(stringField, "Offer Type", out offerType, recordValid);
            result.OfferType = offerType;

            // OfferAcceptanceId
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField,
                                                          ExtractConstants.OfferAcceptanceIdLength, recordValid);
            result.OfferAcceptanceId = stringField;

            // OfferAcceptanceDateTime
            recordValid = parsingUtilities.PopulateDateTime(record, ref recordPos,
                                                            "Offer Acceptance Date\" and \"Offer Acceptance Time", out dateField, true,
                                                            true, recordValid);
            result.OfferAcceptanceDateTime = dateField;

            // RegistrationMid
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField,
                                                          ExtractConstants.RegistrationMidLength, recordValid);
            result.RegistrationMid = stringField;

            // RedemptionMid
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField,
                                                          ExtractConstants.RedemptionMidLength, recordValid);
            result.RedemptionMid = stringField;

            // OfferStartDate
            recordValid = parsingUtilities.PopulateDateTime(record, ref recordPos,
                                                            "Offer Start Date\" and \"Offer Start Time", out dateField, true,
                                                            true, recordValid);
            result.OfferStartDate = dateField;

            // OfferEndDate
            recordValid = parsingUtilities.PopulateDateTime(record, ref recordPos,
                                                            "Offer End Date\" and \"Offer End Time", out dateField, true,
                                                            true, recordValid);
            result.OfferEndDate = dateField;

            // PurchasePrice
            recordValid = parsingUtilities.PopulateDecimal(record, ref recordPos, "Purchase Price", out decimalField,
                                                           ExtractConstants.PurchasePriceLength, recordValid);
            result.PurchasePrice = decimalField;

            // MinimumTransactionAmount
            recordValid = parsingUtilities.PopulateDecimal(record, ref recordPos, "Minimum Transaction Amount", out decimalField,
                                                           ExtractConstants.MinimumTransactionAmountLength, recordValid);
            result.MinimumTransactionAmount = decimalField;

            // DiscountPercentage
            recordValid = parsingUtilities.PopulateDecimal(record, ref recordPos, "Discount Percentage", out decimalField,
                                                           ExtractConstants.DiscountPercentageLength, recordValid);
            result.DiscountPercentage = decimalField;

            // DiscountAmount
            recordValid = parsingUtilities.PopulateDecimal(record, ref recordPos, "Discount Amount", out decimalField,
                                                           ExtractConstants.DiscountAmountLength, recordValid);
            result.DiscountAmount = decimalField;

            // TotalTransactionAmount
            recordValid = parsingUtilities.PopulateDecimal(record, ref recordPos, "Total Transaction Amount", out decimalField,
                                                           ExtractConstants.TotalTransactionAmountLength, recordValid);
            result.TotalTransactionAmount = decimalField;

            // RedemptionDiscountAmount
            recordValid = parsingUtilities.PopulateDecimal(record, ref recordPos, "Redemption Discount Amount", out decimalField,
                                                           ExtractConstants.RedemptionDiscountAmountLength, recordValid);
            result.RedemptionDiscountAmount = decimalField;

            // Record end
            parsingUtilities.VerifyRecordEnd(record, ref recordPos, FillerLength, true, recordValid);

            // If the record is not valid, return a null value.
            if (recordValid == false)
            {
                result = null;
            }

            return(result);
        }
Exemple #10
0
 /// <summary>
 /// Converts the string representation of a chord progression to its <see cref="ChordProgression"/> equivalent.
 /// </summary>
 /// <param name="input">A string containing a chord progression to convert.</param>
 /// <param name="scale">Scale to resolve chords.</param>
 /// <returns>A <see cref="ChordProgression"/> equivalent to the chord progression contained in
 /// <paramref name="input"/>.</returns>
 /// <exception cref="ArgumentException"><paramref name="input"/> is null or contains white-spaces only.</exception>
 /// <exception cref="FormatException"><paramref name="input"/> has invalid format.</exception>
 public static ChordProgression Parse(string input, Scale scale)
 {
     return(ParsingUtilities.Parse(input, GetParsing(input, scale)));
 }
Exemple #11
0
 /// <summary>
 /// Converts the string representation of a musical interval to its <see cref="Interval"/> equivalent.
 /// A return value indicates whether the conversion succeeded.
 /// </summary>
 /// <param name="input">A string containing an interval to convert.</param>
 /// <param name="interval">When this method returns, contains the <see cref="Interval"/>
 /// equivalent of the musical interval contained in <paramref name="input"/>, if the conversion succeeded,
 /// or null if the conversion failed. The conversion fails if the <paramref name="input"/> is null or
 /// <see cref="string.Empty"/>, or is not of the correct format. This parameter is passed uninitialized;
 /// any value originally supplied in result will be overwritten.</param>
 /// <returns>true if <paramref name="input"/> was converted successfully; otherwise, false.</returns>
 public static bool TryParse(string input, out Interval interval)
 {
     return(ParsingUtilities.TryParse(input, IntervalParser.TryParse, out interval));
 }
Exemple #12
0
 /// <summary>
 /// Converts the string representation of a chord progression to its <see cref="ChordProgression"/> equivalent.
 /// A return value indicates whether the conversion succeeded.
 /// </summary>
 /// <param name="input">A string containing a chord progression to convert.</param>
 /// <param name="scale">Scale to resolve chords.</param>
 /// <param name="chordProgression">When this method returns, contains the <see cref="ChordProgression"/>
 /// equivalent of the chord progression contained in <paramref name="input"/>, if the conversion succeeded,
 /// or null if the conversion failed. The conversion fails if the <paramref name="input"/> is null or
 /// <see cref="string.Empty"/>, or is not of the correct format. This parameter is passed uninitialized;
 /// any value originally supplied in result will be overwritten.</param>
 /// <returns>true if <paramref name="input"/> was converted successfully; otherwise, false.</returns>
 public static bool TryParse(string input, Scale scale, out ChordProgression chordProgression)
 {
     return(ParsingUtilities.TryParse(input, GetParsing(input, scale), out chordProgression));
 }
Exemple #13
0
        private void ShowContextMenu()
        {
            ToolStripMenuItem resetVariablesItem = new ToolStripMenuItem("Reset Variables");

            resetVariablesItem.Click += (sender, e) => ResetVariables();

            ToolStripMenuItem clearAllButHighlightedItem = new ToolStripMenuItem("Clear All But Highlighted");

            clearAllButHighlightedItem.Click += (sender, e) => ClearAllButHighlightedVariables();

            ToolStripMenuItem fixVerticalScrollItem = new ToolStripMenuItem("Fix Vertical Scroll");

            fixVerticalScrollItem.Click += (sender, e) => FixVerticalScroll();

            ToolStripMenuItem addCustomVariablesItem = new ToolStripMenuItem("Add Custom Variables");

            addCustomVariablesItem.Click += (sender, e) =>
            {
                VariableCreationForm form = new VariableCreationForm();
                form.Initialize(this);
                form.Show();
            };

            ToolStripMenuItem addMappingVariablesItem = new ToolStripMenuItem("Add Mapping Variables");

            addMappingVariablesItem.Click += (sender, e) => AddVariables(MappingConfig.GetVariables());

            ToolStripMenuItem addDummyVariableItem = new ToolStripMenuItem("Add Dummy Variable...");

            foreach (string typeString in TypeUtilities.InGameTypeList)
            {
                ToolStripMenuItem typeItem = new ToolStripMenuItem(typeString);
                addDummyVariableItem.DropDownItems.Add(typeItem);
                typeItem.Click += (sender, e) =>
                {
                    int numEntries = 1;
                    if (KeyboardUtilities.IsCtrlHeld())
                    {
                        string numEntriesString = DialogUtilities.GetStringFromDialog(labelText: "Enter Num Vars:");
                        if (numEntriesString == null)
                        {
                            return;
                        }
                        int parsed = ParsingUtilities.ParseInt(numEntriesString);
                        parsed     = Math.Max(parsed, 0);
                        numEntries = parsed;
                    }

                    List <WatchVariableControl> controls = new List <WatchVariableControl>();
                    for (int i = 0; i < numEntries; i++)
                    {
                        string        specialType   = WatchVariableSpecialUtilities.AddDummyEntry(typeString);
                        WatchVariable watchVariable =
                            new WatchVariable(
                                memoryTypeName: null,
                                specialType: specialType,
                                baseAddressType: BaseAddressTypeEnum.None,
                                offsetUS: null,
                                offsetJP: null,
                                offsetSH: null,
                                offsetEU: null,
                                offsetDefault: null,
                                mask: null,
                                shift: null,
                                handleMapping: true);
                        WatchVariableControlPrecursor precursor =
                            new WatchVariableControlPrecursor(
                                name: specialType,
                                watchVar: watchVariable,
                                subclass: WatchVariableSubclass.Number,
                                backgroundColor: null,
                                displayType: null,
                                roundingLimit: null,
                                useHex: null,
                                invertBool: null,
                                isYaw: null,
                                coordinate: null,
                                groupList: new List <VariableGroup>()
                        {
                            VariableGroup.Custom
                        });
                        WatchVariableControl control = precursor.CreateWatchVariableControl();
                        controls.Add(control);
                    }
                    AddVariables(controls);
                };
            }

            ToolStripMenuItem openSaveClearItem = new ToolStripMenuItem("Open / Save / Clear ...");

            ControlUtilities.AddDropDownItems(
                openSaveClearItem,
                new List <string>()
            {
                "Open", "Open as Pop Out", "Save in Place", "Save As", "Clear"
            },
                new List <Action>()
            {
                () => OpenVariables(),
                () => OpenVariablesAsPopOut(),
                () => SaveVariablesInPlace(),
                () => SaveVariables(),
                () => ClearVariables(),
            });

            ToolStripMenuItem doToAllVariablesItem = new ToolStripMenuItem("Do to all variables...");

            WatchVariableSelectionUtilities.CreateSelectionToolStripItems(
                () => GetCurrentVariableControls(), this)
            .ForEach(item => doToAllVariablesItem.DropDownItems.Add(item));

            filterVariablesItem.DropDown.MouseEnter += (sender, e) =>
            {
                filterVariablesItem.DropDown.AutoClose = false;
            };
            filterVariablesItem.DropDown.MouseLeave += (sender, e) =>
            {
                filterVariablesItem.DropDown.AutoClose = true;
                filterVariablesItem.DropDown.Close();
            };

            var strip = new ContextMenuStrip();

            strip.Items.Add(resetVariablesItem);
            strip.Items.Add(clearAllButHighlightedItem);
            strip.Items.Add(fixVerticalScrollItem);
            strip.Items.Add(addCustomVariablesItem);
            strip.Items.Add(addMappingVariablesItem);
            strip.Items.Add(addDummyVariableItem);
            strip.Items.Add(openSaveClearItem);
            strip.Items.Add(doToAllVariablesItem);
            strip.Items.Add(filterVariablesItem);
            strip.Show(Cursor.Position);
        }
        public static List <ToolStripItem> CreateSelectionToolStripItems(
            Func <List <WatchVariableControl> > getVars,
            WatchVariableFlowLayoutPanel panel)
        {
            Action <WatchVariableControlSettings, List <WatchVariableControl> > apply2 =
                (WatchVariableControlSettings settings, List <WatchVariableControl> vars) =>
            {
                if (KeyboardUtilities.IsCtrlHeld())
                {
                    WatchVariableControlSettingsManager.AddSettings(settings);
                }
                else
                {
                    vars.ForEach(control => control.ApplySettings(settings));
                }
            };

            Action <WatchVariableControlSettings> apply = (WatchVariableControlSettings settings) => apply2(settings, getVars());

            ToolStripMenuItem itemHighlight = new ToolStripMenuItem("Highlight...");

            ControlUtilities.AddDropDownItems(
                itemHighlight,
                new List <string>()
            {
                "Highlight", "Don't Highlight"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeHighlighted: true, newHighlighted: true)),
                () => apply(new WatchVariableControlSettings(changeHighlighted: true, newHighlighted: false)),
            });
            ToolStripMenuItem itemHighlightColor = new ToolStripMenuItem("Color...");

            ControlUtilities.AddDropDownItems(
                itemHighlightColor,
                new List <string>()
            {
                "Red",
                "Orange",
                "Yellow",
                "Green",
                "Blue",
                "Purple",
                "Pink",
                "Brown",
                "Black",
                "White",
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeHighlightColor: true, newHighlightColor: Color.Red)),
                () => apply(new WatchVariableControlSettings(changeHighlightColor: true, newHighlightColor: Color.Orange)),
                () => apply(new WatchVariableControlSettings(changeHighlightColor: true, newHighlightColor: Color.Yellow)),
                () => apply(new WatchVariableControlSettings(changeHighlightColor: true, newHighlightColor: Color.Green)),
                () => apply(new WatchVariableControlSettings(changeHighlightColor: true, newHighlightColor: Color.Blue)),
                () => apply(new WatchVariableControlSettings(changeHighlightColor: true, newHighlightColor: Color.Purple)),
                () => apply(new WatchVariableControlSettings(changeHighlightColor: true, newHighlightColor: Color.Pink)),
                () => apply(new WatchVariableControlSettings(changeHighlightColor: true, newHighlightColor: Color.Brown)),
                () => apply(new WatchVariableControlSettings(changeHighlightColor: true, newHighlightColor: Color.Black)),
                () => apply(new WatchVariableControlSettings(changeHighlightColor: true, newHighlightColor: Color.White)),
            });
            itemHighlight.DropDownItems.Add(itemHighlightColor);

            ToolStripMenuItem itemLock = new ToolStripMenuItem("Lock...");

            ControlUtilities.AddDropDownItems(
                itemLock,
                new List <string>()
            {
                "Lock", "Don't Lock"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeLocked: true, newLocked: true)),
                () => apply(new WatchVariableControlSettings(changeLocked: true, newLocked: false)),
            });

            ToolStripMenuItem itemFixAddress = new ToolStripMenuItem("Fix Address...");

            ControlUtilities.AddDropDownItems(
                itemFixAddress,
                new List <string>()
            {
                "Default", "Fix Address", "Fix Address Special", "Don't Fix Address"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeFixedAddress: true, changeFixedAddressToDefault: true)),
                () => apply(new WatchVariableControlSettings(changeFixedAddress: true, newFixedAddress: true)),
                () => apply(new WatchVariableControlSettings(doFixAddressSpecial: true)),
                () => apply(new WatchVariableControlSettings(changeFixedAddress: true, newFixedAddress: false)),
            });

            ToolStripMenuItem itemCopy = new ToolStripMenuItem("Copy...");

            CopyUtilities.AddDropDownItems(itemCopy, getVars);

            ToolStripMenuItem itemPaste = new ToolStripMenuItem("Paste");

            itemPaste.Click += (sender, e) => PasteUtilities.Paste(getVars());

            ToolStripMenuItem itemRoundTo        = new ToolStripMenuItem("Round to...");
            ToolStripMenuItem itemRoundToDefault = new ToolStripMenuItem("Default");

            itemRoundToDefault.Click += (sender, e) =>
                                        apply(new WatchVariableControlSettings(
                                                  changeRoundingLimit: true, changeRoundingLimitToDefault: true));
            ToolStripMenuItem itemRoundToNoRounding = new ToolStripMenuItem("No Rounding");

            itemRoundToNoRounding.Click += (sender, e) =>
                                           apply(new WatchVariableControlSettings(
                                                     changeRoundingLimit: true, newRoundingLimit: -1));
            List <ToolStripMenuItem> itemsRoundToNumDecimalPlaces = new List <ToolStripMenuItem>();

            for (int i = 0; i <= 10; i++)
            {
                int index = i;
                itemsRoundToNumDecimalPlaces.Add(new ToolStripMenuItem(index + " decimal place(s)"));
                itemsRoundToNumDecimalPlaces[index].Click += (sender, e) =>
                                                             apply(new WatchVariableControlSettings(
                                                                       changeRoundingLimit: true, newRoundingLimit: index));
            }
            itemRoundTo.DropDownItems.Add(itemRoundToDefault);
            itemRoundTo.DropDownItems.Add(itemRoundToNoRounding);
            itemsRoundToNumDecimalPlaces.ForEach(setAllRoundingLimitsNumberItem =>
            {
                itemRoundTo.DropDownItems.Add(setAllRoundingLimitsNumberItem);
            });

            ToolStripMenuItem itemDisplayAsHex = new ToolStripMenuItem("Display as Hex...");

            ControlUtilities.AddDropDownItems(
                itemDisplayAsHex,
                new List <string>()
            {
                "Default", "Hex", "Decimal"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeDisplayAsHex: true, changeDisplayAsHexToDefault: true)),
                () => apply(new WatchVariableControlSettings(changeDisplayAsHex: true, newDisplayAsHex: true)),
                () => apply(new WatchVariableControlSettings(changeDisplayAsHex: true, newDisplayAsHex: false)),
            });

            ToolStripMenuItem itemAngleSigned = new ToolStripMenuItem("Angle: Signed...");

            ControlUtilities.AddDropDownItems(
                itemAngleSigned,
                new List <string>()
            {
                "Default", "Unsigned", "Signed"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeAngleSigned: true, changeAngleSignedToDefault: true)),
                () => apply(new WatchVariableControlSettings(changeAngleSigned: true, newAngleSigned: false)),
                () => apply(new WatchVariableControlSettings(changeAngleSigned: true, newAngleSigned: true)),
            });

            ToolStripMenuItem itemAngleUnits        = new ToolStripMenuItem("Angle: Units...");
            ToolStripMenuItem itemAngleUnitsDefault = new ToolStripMenuItem("Default");

            itemAngleUnitsDefault.Click += (sender, e) =>
                                           apply(new WatchVariableControlSettings(
                                                     changeAngleUnits: true, changeAngleUnitsToDefault: true));
            List <ToolStripMenuItem> itemsAngleUnitsValue = new List <ToolStripMenuItem>();

            foreach (AngleUnitType angleUnitType in Enum.GetValues(typeof(AngleUnitType)))
            {
                AngleUnitType angleUnitTypeFixed = angleUnitType;
                string        stringValue        = angleUnitTypeFixed.ToString();
                if (stringValue == AngleUnitType.InGameUnits.ToString())
                {
                    stringValue = "In-Game Units";
                }
                ToolStripMenuItem itemAngleUnitsValue = new ToolStripMenuItem(stringValue);
                itemAngleUnitsValue.Click += (sender, e) =>
                                             apply(new WatchVariableControlSettings(
                                                       changeAngleUnits: true, newAngleUnits: angleUnitTypeFixed));
                itemsAngleUnitsValue.Add(itemAngleUnitsValue);
            }
            itemAngleUnits.DropDownItems.Add(itemAngleUnitsDefault);
            itemsAngleUnitsValue.ForEach(setAllAngleUnitsValuesItem =>
            {
                itemAngleUnits.DropDownItems.Add(setAllAngleUnitsValuesItem);
            });

            ToolStripMenuItem itemAngleTruncateToMultipleOf16 = new ToolStripMenuItem("Angle: Truncate to Multiple of 16...");

            ControlUtilities.AddDropDownItems(
                itemAngleTruncateToMultipleOf16,
                new List <string>()
            {
                "Default", "Truncate to Multiple of 16", "Don't Truncate to Multiple of 16"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeAngleTruncateToMultipleOf16: true, changeAngleTruncateToMultipleOf16ToDefault: true)),
                () => apply(new WatchVariableControlSettings(changeAngleTruncateToMultipleOf16: true, newAngleTruncateToMultipleOf16: true)),
                () => apply(new WatchVariableControlSettings(changeAngleTruncateToMultipleOf16: true, newAngleTruncateToMultipleOf16: false)),
            });

            ToolStripMenuItem itemAngleConstrainToOneRevolution = new ToolStripMenuItem("Angle: Constrain to One Revolution...");

            ControlUtilities.AddDropDownItems(
                itemAngleConstrainToOneRevolution,
                new List <string>()
            {
                "Default", "Constrain to One Revolution", "Don't Constrain to One Revolution"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeAngleConstrainToOneRevolution: true, changeAngleConstrainToOneRevolutionToDefault: true)),
                () => apply(new WatchVariableControlSettings(changeAngleConstrainToOneRevolution: true, newAngleConstrainToOneRevolution: true)),
                () => apply(new WatchVariableControlSettings(changeAngleConstrainToOneRevolution: true, newAngleConstrainToOneRevolution: false)),
            });

            ToolStripMenuItem itemAngleReverse = new ToolStripMenuItem("Angle: Reverse...");

            ControlUtilities.AddDropDownItems(
                itemAngleReverse,
                new List <string>()
            {
                "Default", "Reverse", "Don't Reverse"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeAngleReverse: true, changeAngleReverseToDefault: true)),
                () => apply(new WatchVariableControlSettings(changeAngleReverse: true, newAngleReverse: true)),
                () => apply(new WatchVariableControlSettings(changeAngleReverse: true, newAngleReverse: false)),
            });

            ToolStripMenuItem itemAngleDisplayAsHex = new ToolStripMenuItem("Angle: Display as Hex...");

            ControlUtilities.AddDropDownItems(
                itemAngleDisplayAsHex,
                new List <string>()
            {
                "Default", "Hex", "Decimal"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeAngleDisplayAsHex: true, changeAngleDisplayAsHexToDefault: true)),
                () => apply(new WatchVariableControlSettings(changeAngleDisplayAsHex: true, newAngleDisplayAsHex: true)),
                () => apply(new WatchVariableControlSettings(changeAngleDisplayAsHex: true, newAngleDisplayAsHex: false)),
            });

            ToolStripMenuItem itemShowVariableXml = new ToolStripMenuItem("Show Variable XML");

            itemShowVariableXml.Click += (sender, e) =>
            {
                InfoForm infoForm = new InfoForm();
                infoForm.SetText(
                    "Variable Info",
                    "Variable XML",
                    String.Join("\r\n", getVars().ConvertAll(control => control.ToXml(true))));
                infoForm.Show();
            };

            ToolStripMenuItem itemShowVariableInfo = new ToolStripMenuItem("Show Variable Info");

            itemShowVariableInfo.Click += (sender, e) =>
            {
                InfoForm infoForm = new InfoForm();
                infoForm.SetText(
                    "Variable Info",
                    "Variable Info",
                    String.Join("\t",
                                WatchVariableWrapper.GetVarInfoLabels()) +
                    "\r\n" +
                    String.Join(
                        "\r\n",
                        getVars().ConvertAll(control => control.GetVarInfo())
                        .ConvertAll(infoList => String.Join("\t", infoList))));
                infoForm.Show();
            };

            void createBinaryMathOperationVariable(BinaryMathOperation operation)
            {
                List <WatchVariableControl> controls = getVars();

                if (controls.Count % 2 == 1)
                {
                    controls.RemoveAt(controls.Count - 1);
                }

                for (int i = 0; i < controls.Count / 2; i++)
                {
                    WatchVariableControl control1 = controls[i];
                    WatchVariableControl control2 = controls[i + controls.Count / 2];
                    string specialType            = WatchVariableSpecialUtilities.AddBinaryMathOperationEntry(control1, control2, operation);
                    string name = string.Format("{0} {1} {2}", control1.VarName, MathOperationUtilities.GetSymbol(operation), control2.VarName);

                    WatchVariable watchVariable =
                        new WatchVariable(
                            name: name,
                            memoryTypeName: null,
                            specialType: specialType,
                            baseAddressType: BaseAddressTypeEnum.None,
                            offsetUS: null,
                            offsetJP: null,
                            offsetSH: null,
                            offsetEU: null,
                            offsetDefault: null,
                            mask: null,
                            shift: null,
                            handleMapping: true);
                    WatchVariableControlPrecursor precursor =
                        new WatchVariableControlPrecursor(
                            name: name,
                            watchVar: watchVariable,
                            subclass: WatchVariableSubclass.Number,
                            backgroundColor: null,
                            displayType: null,
                            roundingLimit: null,
                            useHex: null,
                            invertBool: null,
                            isYaw: null,
                            coordinate: null,
                            groupList: new List <VariableGroup>()
                    {
                        VariableGroup.Custom
                    });
                    WatchVariableControl control = precursor.CreateWatchVariableControl();
                    panel.AddVariable(control);
                }
            }

            void createAggregateMathOperationVariable(AggregateMathOperation operation)
            {
                List <WatchVariableControl> controls = getVars();

                if (controls.Count == 0)
                {
                    return;
                }
                string        specialType   = WatchVariableSpecialUtilities.AddAggregateMathOperationEntry(controls, operation);
                string        name          = operation.ToString();
                WatchVariable watchVariable =
                    new WatchVariable(
                        name: name,
                        memoryTypeName: null,
                        specialType: specialType,
                        baseAddressType: BaseAddressTypeEnum.None,
                        offsetUS: null,
                        offsetJP: null,
                        offsetSH: null,
                        offsetEU: null,
                        offsetDefault: null,
                        mask: null,
                        shift: null,
                        handleMapping: true);
                WatchVariableControlPrecursor precursor =
                    new WatchVariableControlPrecursor(
                        name: name,
                        watchVar: watchVariable,
                        subclass: WatchVariableSubclass.Number,
                        backgroundColor: null,
                        displayType: null,
                        roundingLimit: null,
                        useHex: null,
                        invertBool: null,
                        isYaw: null,
                        coordinate: null,
                        groupList: new List <VariableGroup>()
                {
                    VariableGroup.Custom
                });
                WatchVariableControl control = precursor.CreateWatchVariableControl();

                panel.AddVariable(control);
            }

            void createDistanceMathOperationVariable(bool use3D)
            {
                List <WatchVariableControl> controls = getVars();
                bool satisfies2D = !use3D && controls.Count >= 4;
                bool satisfies3D = use3D && controls.Count >= 6;

                if (!satisfies2D && !satisfies3D)
                {
                    return;
                }
                string specialType = WatchVariableSpecialUtilities.AddDistanceMathOperationEntry(controls, use3D);
                string name        = use3D ?
                                     string.Format(
                    "({0},{1},{2}) to ({3},{4},{5})",
                    controls[0].VarName,
                    controls[1].VarName,
                    controls[2].VarName,
                    controls[3].VarName,
                    controls[4].VarName,
                    controls[5].VarName) :
                                     string.Format(
                    "({0},{1}) to ({2},{3})",
                    controls[0].VarName,
                    controls[1].VarName,
                    controls[2].VarName,
                    controls[3].VarName);
                WatchVariable watchVariable =
                    new WatchVariable(
                        name: name,
                        memoryTypeName: null,
                        specialType: specialType,
                        baseAddressType: BaseAddressTypeEnum.None,
                        offsetUS: null,
                        offsetJP: null,
                        offsetSH: null,
                        offsetEU: null,
                        offsetDefault: null,
                        mask: null,
                        shift: null,
                        handleMapping: true);
                WatchVariableControlPrecursor precursor =
                    new WatchVariableControlPrecursor(
                        name: name,
                        watchVar: watchVariable,
                        subclass: WatchVariableSubclass.Number,
                        backgroundColor: null,
                        displayType: null,
                        roundingLimit: null,
                        useHex: null,
                        invertBool: null,
                        isYaw: null,
                        coordinate: null,
                        groupList: new List <VariableGroup>()
                {
                    VariableGroup.Custom
                });
                WatchVariableControl control = precursor.CreateWatchVariableControl();

                panel.AddVariable(control);
            }

            void createRealTimeVariable()
            {
                List <WatchVariableControl> controls = getVars();

                for (int i = 0; i < controls.Count; i++)
                {
                    WatchVariableControl control = controls[i];
                    string specialType           = WatchVariableSpecialUtilities.AddRealTimeEntry(control);
                    string name = string.Format("{0} Real Time", control.VarName);

                    WatchVariable watchVariable =
                        new WatchVariable(
                            name: name,
                            memoryTypeName: null,
                            specialType: specialType,
                            baseAddressType: BaseAddressTypeEnum.None,
                            offsetUS: null,
                            offsetJP: null,
                            offsetSH: null,
                            offsetEU: null,
                            offsetDefault: null,
                            mask: null,
                            shift: null,
                            handleMapping: true);
                    WatchVariableControlPrecursor precursor =
                        new WatchVariableControlPrecursor(
                            name: name,
                            watchVar: watchVariable,
                            subclass: WatchVariableSubclass.String,
                            backgroundColor: null,
                            displayType: null,
                            roundingLimit: null,
                            useHex: null,
                            invertBool: null,
                            isYaw: null,
                            coordinate: null,
                            groupList: new List <VariableGroup>()
                    {
                        VariableGroup.Custom
                    });
                    WatchVariableControl control2 = precursor.CreateWatchVariableControl();
                    panel.AddVariable(control2);
                }
            }

            void createActionDescriptionVariable()
            {
                List <WatchVariableControl> controls = getVars();

                for (int i = 0; i < controls.Count; i++)
                {
                    WatchVariableControl control = controls[i];
                    string specialType           = WatchVariableSpecialUtilities.AddActionDescriptionEntry(control);
                    string name = string.Format("{0} Description", control.VarName);

                    WatchVariable watchVariable =
                        new WatchVariable(
                            name: name,
                            memoryTypeName: null,
                            specialType: specialType,
                            baseAddressType: BaseAddressTypeEnum.None,
                            offsetUS: null,
                            offsetJP: null,
                            offsetSH: null,
                            offsetEU: null,
                            offsetDefault: null,
                            mask: null,
                            shift: null,
                            handleMapping: true);
                    WatchVariableControlPrecursor precursor =
                        new WatchVariableControlPrecursor(
                            name: name,
                            watchVar: watchVariable,
                            subclass: WatchVariableSubclass.String,
                            backgroundColor: null,
                            displayType: null,
                            roundingLimit: null,
                            useHex: null,
                            invertBool: null,
                            isYaw: null,
                            coordinate: null,
                            groupList: new List <VariableGroup>()
                    {
                        VariableGroup.Custom
                    });
                    WatchVariableControl control2 = precursor.CreateWatchVariableControl();
                    panel.AddVariable(control2);
                }
            }

            void createDereferencedVariable(string typeString)
            {
                List <WatchVariableControl> controls = getVars();
                uint?offset = null;

                if (KeyboardUtilities.IsCtrlHeld())
                {
                    string offsetString = DialogUtilities.GetStringFromDialog(labelText: "Enter Offset in Hex:");
                    if (offsetString != null)
                    {
                        offset = ParsingUtilities.ParseHexNullable(offsetString);
                    }
                }
                for (int i = 0; i < controls.Count; i++)
                {
                    WatchVariableControl control = controls[i];
                    string specialType           = WatchVariableSpecialUtilities.AddDereferencedEntry(control, typeString, offset);
                    string name = string.Format("{0}{1} Deref", control.VarName, offset.HasValue ? " + " + HexUtilities.FormatValue(offset.Value) : "");

                    WatchVariable watchVariable =
                        new WatchVariable(
                            name: name,
                            memoryTypeName: null,
                            specialType: specialType,
                            baseAddressType: BaseAddressTypeEnum.None,
                            offsetUS: null,
                            offsetJP: null,
                            offsetSH: null,
                            offsetEU: null,
                            offsetDefault: null,
                            mask: null,
                            shift: null,
                            handleMapping: true);
                    WatchVariableControlPrecursor precursor =
                        new WatchVariableControlPrecursor(
                            name: name,
                            watchVar: watchVariable,
                            subclass: WatchVariableSubclass.Number,
                            backgroundColor: null,
                            displayType: null,
                            roundingLimit: null,
                            useHex: null,
                            invertBool: null,
                            isYaw: null,
                            coordinate: null,
                            groupList: new List <VariableGroup>()
                    {
                        VariableGroup.Custom
                    });
                    WatchVariableControl control2 = precursor.CreateWatchVariableControl();
                    panel.AddVariable(control2);
                }
            }

            ToolStripMenuItem itemAddDereferencedVariable = new ToolStripMenuItem("Dereferenced...");

            foreach (string typeString in TypeUtilities.InGameTypeList)
            {
                ToolStripMenuItem typeItem = new ToolStripMenuItem(typeString);
                itemAddDereferencedVariable.DropDownItems.Add(typeItem);
                typeItem.Click += (sender, e) =>
                {
                    createDereferencedVariable(typeString);
                };
            }
            ToolStripMenuItem itemAddVariables = new ToolStripMenuItem("Add Variable(s)...");

            ControlUtilities.AddDropDownItems(
                itemAddVariables,
                new List <string>()
            {
                "Addition",
                "Subtraction",
                "Multiplication",
                "Division",
                "Modulo",
                "Non-Negative Modulo",
                "Exponent",
                null,
                "Mean",
                "Median",
                "Min",
                "Max",
                "Sum",
                null,
                "2D Distance",
                "3D Distance",
                null,
                "Real Time",
                "Action Description",
            },
                new List <Action>()
            {
                () => createBinaryMathOperationVariable(BinaryMathOperation.Add),
                () => createBinaryMathOperationVariable(BinaryMathOperation.Subtract),
                () => createBinaryMathOperationVariable(BinaryMathOperation.Multiply),
                () => createBinaryMathOperationVariable(BinaryMathOperation.Divide),
                () => createBinaryMathOperationVariable(BinaryMathOperation.Modulo),
                () => createBinaryMathOperationVariable(BinaryMathOperation.NonNegativeModulo),
                () => createBinaryMathOperationVariable(BinaryMathOperation.Exponent),
                () => { },
                () => createAggregateMathOperationVariable(AggregateMathOperation.Mean),
                () => createAggregateMathOperationVariable(AggregateMathOperation.Median),
                () => createAggregateMathOperationVariable(AggregateMathOperation.Min),
                () => createAggregateMathOperationVariable(AggregateMathOperation.Max),
                () => createAggregateMathOperationVariable(AggregateMathOperation.Sum),
                () => { },
                () => createDistanceMathOperationVariable(use3D: false),
                () => createDistanceMathOperationVariable(use3D: true),
                () => { },
                () => createRealTimeVariable(),
                () => createActionDescriptionVariable(),
            });
            itemAddVariables.DropDownItems.Add(itemAddDereferencedVariable);

            ToolStripMenuItem itemSetCascadingValues = new ToolStripMenuItem("Set Cascading Values");

            itemSetCascadingValues.Click += (sender, e) =>
            {
                List <WatchVariableControl> controls = getVars();
                object value1 = DialogUtilities.GetStringFromDialog(labelText: "Base Value:");
                object value2 = DialogUtilities.GetStringFromDialog(labelText: "Offset Value:");
                if (value1 == null || value2 == null)
                {
                    return;
                }
                double?number1 = ParsingUtilities.ParseDoubleNullable(value1);
                double?number2 = ParsingUtilities.ParseDoubleNullable(value2);
                if (!number1.HasValue || !number2.HasValue)
                {
                    return;
                }
                List <Func <object, bool, bool> > setters = controls.SelectMany(control => control.GetSetters()).ToList();
                for (int i = 0; i < setters.Count; i++)
                {
                    setters[i](number1.Value + i * number2.Value, true);
                }
            };

            List <string> backgroundColorStringList = new List <string>();
            List <Action> backgroundColorActionList = new List <Action>();

            backgroundColorStringList.Add("Default");
            backgroundColorActionList.Add(
                () => apply(new WatchVariableControlSettings(changeBackgroundColor: true, changeBackgroundColorToDefault: true)));
            foreach (KeyValuePair <string, string> pair in ColorUtilities.ColorToParamsDictionary)
            {
                Color  color       = ColorTranslator.FromHtml(pair.Value);
                string colorString = pair.Key;
                if (colorString == "LightBlue")
                {
                    colorString = "Light Blue";
                }
                backgroundColorStringList.Add(colorString);
                backgroundColorActionList.Add(
                    () => apply(new WatchVariableControlSettings(changeBackgroundColor: true, newBackgroundColor: color)));
            }
            backgroundColorStringList.Add("Control (No Color)");
            backgroundColorActionList.Add(
                () => apply(new WatchVariableControlSettings(changeBackgroundColor: true, newBackgroundColor: SystemColors.Control)));
            backgroundColorStringList.Add("Custom Color");
            backgroundColorActionList.Add(
                () =>
            {
                List <WatchVariableControl> vars = getVars();
                Color?newColor = ColorUtilities.GetColorFromDialog(SystemColors.Control);
                if (newColor.HasValue)
                {
                    apply2(new WatchVariableControlSettings(changeBackgroundColor: true, newBackgroundColor: newColor.Value), vars);
                    ColorUtilities.LastCustomColor = newColor.Value;
                }
            });
            backgroundColorStringList.Add("Last Custom Color");
            backgroundColorActionList.Add(
                () => apply(new WatchVariableControlSettings(changeBackgroundColor: true, newBackgroundColor: ColorUtilities.LastCustomColor)));
            ToolStripMenuItem itemBackgroundColor = new ToolStripMenuItem("Background Color...");

            ControlUtilities.AddDropDownItems(
                itemBackgroundColor,
                backgroundColorStringList,
                backgroundColorActionList);

            ToolStripMenuItem itemMove = new ToolStripMenuItem("Move...");

            ControlUtilities.AddDropDownItems(
                itemMove,
                new List <string>()
            {
                "Start Move", "End Move", "Clear Move"
            },
                new List <Action>()
            {
                () => panel.NotifyOfReorderingStart(getVars()),
                () => panel.NotifyOfReorderingEnd(getVars()),
                () => panel.NotifyOfReorderingClear(),
            });

            ToolStripMenuItem itemRemove = new ToolStripMenuItem("Remove");

            itemRemove.Click += (sender, e) => panel.RemoveVariables(getVars());

            ToolStripMenuItem itemRename = new ToolStripMenuItem("Rename...");

            itemRename.Click += (sender, e) =>
            {
                List <WatchVariableControl> watchVars = getVars();
                string template = DialogUtilities.GetStringFromDialog("$");
                if (template == null)
                {
                    return;
                }
                foreach (WatchVariableControl control in watchVars)
                {
                    control.VarName = template.Replace("$", control.VarName);
                }
            };

            ToolStripMenuItem itemOpenController = new ToolStripMenuItem("Open Controller");

            itemOpenController.Click += (sender, e) =>
            {
                List <WatchVariableControl> vars          = getVars();
                VariableControllerForm      varController =
                    new VariableControllerForm(
                        vars.ConvertAll(control => control.VarName),
                        vars.ConvertAll(control => control.WatchVarWrapper),
                        vars.ConvertAll(control => control.FixedAddressListGetter()));
                varController.Show();
            };

            ToolStripMenuItem itemOpenTripletController = new ToolStripMenuItem("Open Triplet Controller");

            itemOpenTripletController.Click += (sender, e) =>
            {
                VariableTripletControllerForm form = new VariableTripletControllerForm();
                form.Initialize(getVars().ConvertAll(control => control.CreateCopy()));
                form.ShowForm();
            };

            ToolStripMenuItem itemOpenPopOut = new ToolStripMenuItem("Open Pop Out");

            itemOpenPopOut.Click += (sender, e) =>
            {
                VariablePopOutForm form = new VariablePopOutForm();
                form.Initialize(getVars().ConvertAll(control => control.CreateCopy()));
                form.ShowForm();
            };

            ToolStripMenuItem itemAddToTab = new ToolStripMenuItem("Add to Tab...");

            ControlUtilities.AddDropDownItems(
                itemAddToTab,
                new List <string>()
            {
                "Regular", "Fixed", "Grouped by Base Address", "Grouped by Variable"
            },
                new List <Action>()
            {
                () => SelectionForm.ShowDataManagerSelectionForm(getVars(), AddToTabTypeEnum.Regular),
                () => SelectionForm.ShowDataManagerSelectionForm(getVars(), AddToTabTypeEnum.Fixed),
                () => SelectionForm.ShowDataManagerSelectionForm(getVars(), AddToTabTypeEnum.GroupedByBaseAddress),
                () => SelectionForm.ShowDataManagerSelectionForm(getVars(), AddToTabTypeEnum.GroupedByVariable),
            });

            ToolStripMenuItem itemAddToCustomTab = new ToolStripMenuItem("Add to Custom Tab...");

            ControlUtilities.AddDropDownItems(
                itemAddToCustomTab,
                new List <string>()
            {
                "Regular", "Fixed", "Grouped by Base Address", "Grouped by Variable"
            },
                new List <Action>()
            {
                () => WatchVariableControl.AddVarsToTab(getVars(), Config.CustomManager, AddToTabTypeEnum.Regular),
                () => WatchVariableControl.AddVarsToTab(getVars(), Config.CustomManager, AddToTabTypeEnum.Fixed),
                () => WatchVariableControl.AddVarsToTab(getVars(), Config.CustomManager, AddToTabTypeEnum.GroupedByBaseAddress),
                () => WatchVariableControl.AddVarsToTab(getVars(), Config.CustomManager, AddToTabTypeEnum.GroupedByVariable),
            });

            return(new List <ToolStripItem>()
            {
                itemHighlight,
                itemLock,
                itemFixAddress,
                itemCopy,
                itemPaste,
                new ToolStripSeparator(),
                itemRoundTo,
                itemDisplayAsHex,
                new ToolStripSeparator(),
                itemAngleSigned,
                itemAngleUnits,
                itemAngleTruncateToMultipleOf16,
                itemAngleConstrainToOneRevolution,
                itemAngleReverse,
                itemAngleDisplayAsHex,
                new ToolStripSeparator(),
                itemShowVariableXml,
                itemShowVariableInfo,
                new ToolStripSeparator(),
                itemAddVariables,
                itemSetCascadingValues,
                new ToolStripSeparator(),
                itemBackgroundColor,
                itemMove,
                itemRemove,
                itemRename,
                itemOpenController,
                itemOpenTripletController,
                itemOpenPopOut,
                itemAddToTab,
                itemAddToCustomTab,
            });
        }
 /// <summary>
 /// Converts the string representation of a musical note to its <see cref="Note"/> equivalent.
 /// </summary>
 /// <param name="input">A string containing a note to convert.</param>
 /// <returns>A <see cref="Note"/> equivalent to the musical note contained in <paramref name="input"/>.</returns>
 /// <exception cref="ArgumentException"><paramref name="input"/> is <c>null</c> or contains white-spaces only.</exception>
 /// <exception cref="FormatException"><paramref name="input"/> has invalid format.</exception>
 public static Note Parse(string input)
 {
     return(ParsingUtilities.Parse <Note>(input, NoteParser.TryParse));
 }
Exemple #16
0
        public void Load()
        {
            // Create new graphics control
            _mapGraphics = new MapGraphics(_mapGui.GLControl);
            _mapGraphics.Load();

            _isLoaded = true;

            // Set the default map
            ChangeCurrentMap(MapAssoc.DefaultMap);

            // Add Mario's map object
            _mapGraphics.AddMapObject(_marioMapObj);
            _mapGraphics.AddMapObject(_holpMapObj);
            _mapGraphics.AddMapObject(_intendedNextPositionMapObj);
            _mapGraphics.AddMapObject(_cameraMapObj);
            _mapGraphics.AddMapObject(_floorTriangleMapObj);
            _mapGraphics.AddMapObject(_ceilingTriangleMapObj);

            //----- Register events ------
            // Set image
            _mapGui.MapIconSizeTrackbar.ValueChanged += (sender, e) => _mapGraphics.IconSize = _mapGui.MapIconSizeTrackbar.Value;

            _mapGui.MapBoundsUpButton.Click        += (sender, e) => ChangeMapPosition(0, 1);
            _mapGui.MapBoundsDownButton.Click      += (sender, e) => ChangeMapPosition(0, -1);
            _mapGui.MapBoundsLeftButton.Click      += (sender, e) => ChangeMapPosition(-1, 0);
            _mapGui.MapBoundsRightButton.Click     += (sender, e) => ChangeMapPosition(1, 0);
            _mapGui.MapBoundsUpLeftButton.Click    += (sender, e) => ChangeMapPosition(-1, 1);
            _mapGui.MapBoundsUpRightButton.Click   += (sender, e) => ChangeMapPosition(1, 1);
            _mapGui.MapBoundsDownLeftButton.Click  += (sender, e) => ChangeMapPosition(-1, -1);
            _mapGui.MapBoundsDownRightButton.Click += (sender, e) => ChangeMapPosition(1, -1);

            _mapGui.MapBoundsZoomInButton.Click  += (sender, e) => ChangeMapZoom(1);
            _mapGui.MapBoundsZoomOutButton.Click += (sender, e) => ChangeMapZoom(-1);

            _mapGui.MapArtificialMarioYLabelTextBox.AddEnterAction(() =>
                                                                   _artificialMarioY = ParsingUtilities.ParseFloatNullable(
                                                                       _mapGui.MapArtificialMarioYLabelTextBox.Text));
        }
Exemple #17
0
        internal static ParsingResult TryParseChordName(Match match, NoteName rootNoteName, out Chord chord)
        {
            chord = null;

            //

            Quality?quality = null;

            var qualityGroup = match.Groups[ChordQualityGroupName];

            if (qualityGroup.Success)
            {
                quality = GroupsQualities.FirstOrDefault(gq => match.Groups[gq.Key].Success).Value;
            }

            //

            var             extensionIntervalNumber  = -1;
            IntervalQuality?extensionIntervalQuality = null;

            var extensionGroup = match.Groups[ExtensionGroupName];

            if (extensionGroup.Success && !string.IsNullOrWhiteSpace(extensionGroup.Value))
            {
                if (match.Groups[ExtensionQualityGroupName].Success)
                {
                    extensionIntervalQuality = GroupsExtensionQualities.FirstOrDefault(gq => match.Groups[gq.Key].Success).Value;
                }

                if (!ParsingUtilities.ParseInt(match, ExtensionNumberGroupName, -1, out extensionIntervalNumber) ||
                    extensionIntervalNumber < 5)
                {
                    return(ParsingResult.Error(ExtensionNumberIsOutOfRange));
                }
            }

            if (quality == Quality.HalfDiminished || quality == Quality.Dominant)
            {
                if (extensionIntervalNumber >= 0 && extensionIntervalNumber != 7)
                {
                    return(ParsingResult.Error(HalfDiminishedOrDominantIsNotSeventh));
                }

                if (extensionIntervalNumber < 0)
                {
                    extensionIntervalNumber = 7;
                }
            }

            var extensionNotes   = new List <NoteName>();
            var extensionNumbers = new List <int>();

            if (extensionIntervalNumber >= 0)
            {
                var extensionNotesDictionary = GetExtensionNotes(quality, rootNoteName, extensionIntervalNumber, extensionIntervalQuality);
                extensionNotes.AddRange(extensionNotesDictionary.Keys);
                extensionNumbers.AddRange(extensionNotesDictionary.Values);
            }

            if (quality == Quality.HalfDiminished)
            {
                quality = Quality.Diminished;
            }
            else if (quality == Quality.Dominant)
            {
                quality = Quality.Major;
            }

            if (quality == null)
            {
                quality = Quality.Major;
            }

            //

            var notes = new List <NoteName>(Chord.GetByTriad(rootNoteName, ChordQualities[quality.Value]).NotesNames);

            notes.AddRange(extensionNotes);
            extensionNumbers.InsertRange(0, new[] { 1, 3, 5 });
            if (extensionIntervalNumber == 5)
            {
                notes.Clear();
                notes.AddRange(new[] { rootNoteName, extensionNotes.First() });

                extensionNumbers.Clear();
                extensionNumbers.AddRange(new[] { 1, 5 });
            }

            //

            var alteredToneGroup = match.Groups[AlteredToneGroupName];

            if (alteredToneGroup.Success)
            {
                int alteredToneNumber;
                if (!ParsingUtilities.ParseInt(match, AlteredToneNumberGroupName, -1, out alteredToneNumber))
                {
                    return(ParsingResult.Error(AlteredToneNumberIsOutOfRange));
                }

                var transposeBy = 0;

                var accidental = match.Groups[AlteredToneAccidentalGroupName].Value;
                switch (accidental)
                {
                case "#":
                case "+":
                    transposeBy = 1;
                    break;

                case "b":
                case "-":
                    transposeBy = -1;
                    break;
                }

                var maxExtensionNumber = extensionNumbers.Max();
                if (maxExtensionNumber < alteredToneNumber)
                {
                    var extensionNotesDictionary = GetExtensionNotes(quality, rootNoteName, alteredToneNumber, null)
                                                   .Where(kv => kv.Value > maxExtensionNumber);

                    notes.AddRange(extensionNotesDictionary.Select(kv => kv.Key));
                    extensionNumbers.AddRange(extensionNotesDictionary.Select(kv => kv.Value));
                }

                var index = extensionNumbers.IndexOf(alteredToneNumber);
                if (index >= 0)
                {
                    notes[index] = notes[index].Transpose(Interval.FromHalfSteps(transposeBy));
                }
            }

            //

            var suspendedGroup = match.Groups[SuspendedGroupName];

            if (suspendedGroup.Success)
            {
                int suspensionNumber;
                if (!ParsingUtilities.ParseInt(match, SuspendedNumberGroupName, -1, out suspensionNumber) ||
                    suspensionNumber != 2 && suspensionNumber != 4)
                {
                    return(ParsingResult.Error(SuspensionNumberIsOutOfRange));
                }

                var interval = suspensionNumber == 2
                    ? Interval.Get(IntervalQuality.Major, 2)
                    : Interval.Get(IntervalQuality.Perfect, 4);
                notes[1] = rootNoteName.Transpose(interval);
            }

            //

            var addedToneGroup = match.Groups[AddedToneGroupName];

            if (addedToneGroup.Success)
            {
                int addedToneNumber;
                if (!ParsingUtilities.ParseInt(match, AddedToneNumberGroupName, -1, out addedToneNumber))
                {
                    return(ParsingResult.Error(AddedToneNumberIsOutOfRange));
                }

                var interval = Interval.IsPerfect(addedToneNumber)
                    ? Interval.Get(IntervalQuality.Perfect, addedToneNumber)
                    : Interval.Get(IntervalQuality.Major, addedToneNumber);
                notes.Add(rootNoteName.Transpose(interval));
            }

            //

            var bassNoteNameGroup = match.Groups[BassNoteNameGroupName];

            if (bassNoteNameGroup.Success)
            {
                NoteName bassNoteName;
                var      bassNoteNameParsingResult = NoteNameParser.TryParse(bassNoteNameGroup.Value, out bassNoteName);
                if (bassNoteNameParsingResult.Status != ParsingStatus.Parsed)
                {
                    return(bassNoteNameParsingResult);
                }

                notes.Insert(0, bassNoteName);
            }

            //

            chord = new Chord(notes);
            return(ParsingResult.Parsed);
        }
Exemple #18
0
        public override void TakeParameters(string line)
        {
            string filePathArg = ParsingUtilities.GetQuoteOneArgument(line);

            filePath = PathTracker.CombineRelativePath(filePathArg);
        }
Exemple #19
0
 /// <summary>
 /// Converts the string representation of a musical chord to its <see cref="Chord"/> equivalent.
 /// A return value indicates whether the conversion succeeded.
 /// </summary>
 /// <param name="input">A string containing a chord to convert.</param>
 /// <param name="chord">When this method returns, contains the <see cref="Chord"/>
 /// equivalent of the musical chord contained in <paramref name="input"/>, if the conversion succeeded,
 /// or null if the conversion failed. The conversion fails if the <paramref name="input"/> is null or
 /// <see cref="string.Empty"/>, or is not of the correct format. This parameter is passed uninitialized;
 /// any value originally supplied in result will be overwritten.</param>
 /// <returns>true if <paramref name="input"/> was converted successfully; otherwise, false.</returns>
 public static bool TryParse(string input, out Chord chord)
 {
     return(ParsingUtilities.TryParse(input, ChordParser.TryParse, out chord));
 }
Exemple #20
0
 /// <summary>
 /// Converts the string representation of a bar/beat time span to its <see cref="BarBeatTicksTimeSpan"/>
 /// equivalent. A return value indicates whether the conversion succeeded.
 /// </summary>
 /// <param name="input">A string containing a time span to convert.</param>
 /// <param name="timeSpan">When this method returns, contains the <see cref="BarBeatTicksTimeSpan"/>
 /// equivalent of the time span contained in <paramref name="input"/>, if the conversion succeeded, or
 /// null if the conversion failed. The conversion fails if the <paramref name="input"/> is null or
 /// <see cref="String.Empty"/>, or is not of the correct format. This parameter is passed uninitialized;
 /// any value originally supplied in result will be overwritten.</param>
 /// <returns>true if <paramref name="input"/> was converted successfully; otherwise, false.</returns>
 public static bool TryParse(string input, out BarBeatTicksTimeSpan timeSpan)
 {
     return(ParsingUtilities.TryParse(input, BarBeatTicksTimeSpanParser.TryParse, out timeSpan));
 }
 private uint?GetCurrentAddress()
 {
     return(ParsingUtilities.ParseHexNullable(textBoxAddressValue.Text));
 }
Exemple #22
0
 /// <summary>
 /// Converts the string representation of a bar/beat time span to its <see cref="BarBeatTicksTimeSpan"/>
 /// equivalent.
 /// </summary>
 /// <param name="input">A string containing a time span to convert.</param>
 /// <returns>A <see cref="BarBeatTicksTimeSpan"/> equivalent to the time span contained in
 /// <paramref name="input"/>.</returns>
 /// <exception cref="ArgumentException"><paramref name="input"/> is null or contains white-spaces only.</exception>
 /// <exception cref="FormatException"><paramref name="input"/> has invalid format.</exception>
 public static BarBeatTicksTimeSpan Parse(string input)
 {
     return(ParsingUtilities.Parse <BarBeatTicksTimeSpan>(input, BarBeatTicksTimeSpanParser.TryParse));
 }
 private ushort?GetCurrentYPosition()
 {
     return(ParsingUtilities.ParseUShortNullable(textBoxYPosValue.Text));
 }
Exemple #24
0
        /// <summary>
        /// Parses the specified record text into a settlement detail object if possible.
        /// </summary>
        /// <param name="record">
        /// The record text to parse into a settlement detail object.
        /// </param>
        /// <param name="recordNumber">
        /// The number of the record of this type from the extract file being parsed.
        /// </param>
        /// <returns>
        /// * The SettlementDetail object if successful.
        /// * Else returns null.
        /// </returns>
        internal SettlementDetail Parse(string record,
                                        int recordNumber)
        {
            SettlementDetail result = new SettlementDetail();

            RecordNumber = recordNumber;

            int      recordPos    = 0;
            bool     recordValid  = true;
            string   stringField  = null;
            DateTime dateField    = DateTime.MinValue;
            decimal  decimalField = Decimal.MinValue;

            ParsingUtilities parsingUtilities = new ParsingUtilities(RecordTypeDescriptor, RecordNumber, FileName, ExtractConstants.TimeFieldLength, Log);

            // RecordType
            recordValid = parsingUtilities.VerifyString(record, ref recordPos, "Record Type", RecordType,
                                                        ExtractConstants.RecordTypeLength, recordValid);

            // ProviderId
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField,
                                                          ExtractConstants.ProviderIdLength, recordValid);
            result.ProviderId = stringField;

            // ProviderLevelNumber
            recordValid = parsingUtilities.VerifyString(record, ref recordPos, "Hierarchy Level No.",
                                                        ExtractConstants.ProviderLevelNumber,
                                                        ExtractConstants.ProviderLevelNumberLength, recordValid);

            // LocationMid
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField,
                                                          ExtractConstants.LocationMidLength, recordValid);
            result.LocationMid = stringField;

            // ChainId
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField, ExtractConstants.ChainIdLength,
                                                          recordValid);
            result.ChainId = stringField;

            // CorporateId
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField,
                                                          ExtractConstants.CorporateIdLength, recordValid);
            result.CorporateId = stringField;

            // TerminalId
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField,
                                                          ExtractConstants.TerminalIdLength, recordValid);
            result.TerminalId = stringField;

            // BankMarker
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField,
                                                          ExtractConstants.BankMarkerLength, recordValid);
            result.BankMarker = stringField;

            // CardSuffix
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField,
                                                          ExtractConstants.CardSuffixLength, recordValid);
            result.CardSuffix = stringField;

            // OfferId
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField, ExtractConstants.OfferIdLength,
                                                          recordValid);
            result.OfferId = stringField;

            // ConsumerId
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField,
                                                          ExtractConstants.ConsumerIdLength, recordValid);
            result.ConsumerId = stringField;

            // TransactionId
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField,
                                                          ExtractConstants.TransactionIdLength, recordValid);
            result.TransactionId = stringField;

            // TransactionType
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField,
                                                          ExtractConstants.TransactionTypeLength, recordValid);
            TransactionType transactionType;

            recordValid            = DetermineTransactionType(stringField, "Transaction Type", out transactionType, recordValid);
            result.TransactionType = transactionType;

            // TransactionDateTime
            recordValid = parsingUtilities.PopulateDateTime(record, ref recordPos, "Transaction Date\" and \"Transaction Time",
                                                            out dateField, true, true, recordValid);
            result.TransactionDateTime = dateField;

            // TotalTransactionAmount
            recordValid = parsingUtilities.PopulateDecimal(record, ref recordPos, "Total Transaction Amount", out decimalField,
                                                           ExtractConstants.TotalTransactionAmountLength, recordValid);
            result.TotalTransactionAmount = decimalField;

            // RedemptionDiscountAmount
            recordValid = parsingUtilities.PopulateDecimal(record, ref recordPos, "Redemption Discount Amount", out decimalField,
                                                           ExtractConstants.RedemptionDiscountAmountLength, recordValid);
            result.RedemptionDiscountAmount = decimalField;

            // CurrencyCode
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField,
                                                          ExtractConstants.CurrencyCodeLength, recordValid);
            result.CurrencyCode = stringField;

            // InvoiceId
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField,
                                                          ExtractConstants.InvoiceIdLength, recordValid);
            result.InvoiceId = stringField;

            // AcquirerReferenceNumber
            recordValid = parsingUtilities.PopulateString(record, ref recordPos, out stringField,
                                                          ExtractConstants.AcquirerReferenceNumberLength, recordValid);
            result.AcquirerReferenceNumber = stringField;

            // Record end
            parsingUtilities.VerifyRecordEnd(record, ref recordPos, FillerLength, true, recordValid);

            // If the record is not valid, return a null value.
            if (recordValid == false)
            {
                result = null;
            }

            return(result);
        }
Exemple #25
0
 private void textBoxSize_EnterAction()
 {
     SetSize(ParsingUtilities.ParseFloatNullable(textBoxSize.Text));
 }
Exemple #26
0
 public void GetPubMedIds_AsExpected(string field, string pubmedIds)
 {
     Assert.Equal(string.Join(',', ParsingUtilities.GetPubMedIds(field, MitoMapInputDb)), pubmedIds);
 }
Exemple #27
0
        public static List <TtcObject> CreateRngObjectsFromGame(TtcRng rng, List <int> dustFrames = null)
        {
            Func <int, uint> getOffset = (int i) => (uint)i * 0x260;

            List <TtcObject> rngObjects = new List <TtcObject>();

            for (int i = 0; i < 6; i++)
            {
                rngObjects.Add(new TtcRotatingBlock(rng, 0x8033D488 + getOffset(i)).SetIndex(i + 1));
            }
            for (int i = 0; i < 2; i++)
            {
                rngObjects.Add(new TtcRotatingTriangularPrism(rng, 0x8033E2C8 + getOffset(i)).SetIndex(i + 1));
            }
            for (int i = 0; i < 4; i++)
            {
                rngObjects.Add(new TtcPendulum(rng, 0x8033E788 + getOffset(i)).SetIndex(i + 1));
            }
            for (int i = 0; i < 5; i++)
            {
                rngObjects.Add(new TtcTreadmill(rng, 0x8033F108 + getOffset(i)).SetIndex(i + 1));
            }
            for (int i = 0; i < 12; i++)
            {
                rngObjects.Add(new TtcPusher(rng, 0x8033FCE8 + getOffset(i)).SetIndex(i + 1));
            }
            for (int i = 0; i < 5; i++)
            {
                rngObjects.Add(new TtcCog(rng, 0x80341968 + getOffset(i)).SetIndex(i + 1));
            }
            for (int i = 0; i < 2; i++)
            {
                rngObjects.Add(new TtcSpinningTriangle(rng, 0x80342548 + getOffset(i)).SetIndex(i + 1));
            }
            for (int i = 0; i < 1; i++)
            {
                rngObjects.Add(new TtcPitBlock(rng, 0x80342A08 + getOffset(i)).SetIndex(i + 1));
            }
            for (int i = 0; i < 2; i++)
            {
                rngObjects.Add(new TtcHand(rng, 0x80342C68 + getOffset(i)).SetIndex(i + 1));
            }
            for (int i = 0; i < 14; i++)
            {
                rngObjects.Add(new TtcSpinner(rng, 0x80343128 + getOffset(i)).SetIndex(i + 1));
            }
            for (int i = 0; i < 6; i++)
            {
                rngObjects.Add(new TtcWheel(rng, 0x80345268 + getOffset(i)).SetIndex(i + 1));
            }
            for (int i = 0; i < 2; i++)
            {
                rngObjects.Add(new TtcElevator(rng, 0x80347608 + getOffset(i)).SetIndex(i + 1));
            }
            for (int i = 0; i < 1; i++)
            {
                rngObjects.Add(new TtcCog(rng, 0x8034B3C8 + getOffset(i)).SetIndex(i + 6));
            }
            for (int i = 0; i < 2; i++)
            {
                rngObjects.Add(new TtcTreadmill(rng, 0x8034D508 + getOffset(i)).SetIndex(i + 6));
            }
            for (int i = 0; i < 1; i++)
            {
                rngObjects.Add(new TtcThwomp(rng, 0x8034E808 + getOffset(i)).SetIndex(i + 1));
            }
            for (int i = 0; i < 2; i++)
            {
                if (i == 0)
                {
                    rngObjects.Add(new TtcAmp(rng, 0x80347AC8).SetIndex(i + 1));
                }
                if (i == 1)
                {
                    rngObjects.Add(new TtcAmp(rng, 0x8034A328).SetIndex(i + 1));
                }
            }
            List <ObjectDataModel> bobombs = Config.ObjectSlotsManager.GetLoadedObjectsWithName("Bob-omb");

            bobombs.Sort((obj1, obj2) =>
            {
                string label1 = Config.ObjectSlotsManager.GetSlotLabelFromObject(obj1);
                string label2 = Config.ObjectSlotsManager.GetSlotLabelFromObject(obj2);
                int pos1      = ParsingUtilities.ParseInt(label1);
                int pos2      = ParsingUtilities.ParseInt(label2);
                return(pos1 - pos2);
            });
            for (int i = 0; i < bobombs.Count; i++)
            {
                rngObjects.Add(new TtcBobomb(rng, bobombs[i].Address).SetIndex(i + 1));
            }
            for (int i = 0; i < 1; i++)
            {
                TtcDust dust = new TtcDust(rng).SetIndex(i + 1) as TtcDust;
                if (dustFrames != null)
                {
                    dust.AddDustFrames(dustFrames);
                }
                rngObjects.Add(dust);
            }
            return(rngObjects);
        }
 /// <summary>
 /// Converts the string representation of a musical note to its <see cref="Note"/> equivalent.
 /// A return value indicates whether the conversion succeeded.
 /// </summary>
 /// <param name="input">A string containing a note to convert.</param>
 /// <param name="note">When this method returns, contains the <see cref="Note"/>
 /// equivalent of the musical note contained in <paramref name="input"/>, if the conversion succeeded,
 /// or <c>null</c> if the conversion failed. The conversion fails if the <paramref name="input"/> is <c>null</c> or
 /// <see cref="string.Empty"/>, or is not of the correct format. This parameter is passed uninitialized;
 /// any value originally supplied in result will be overwritten.</param>
 /// <returns><c>true</c> if <paramref name="input"/> was converted successfully; otherwise, <c>false</c>.</returns>
 public static bool TryParse(string input, out Note note)
 {
     return(ParsingUtilities.TryParse(input, NoteParser.TryParse, out note));
 }
        public static byte[] GetBytesFromString(this WatchVariable watchVar, ProcessStream stream, uint offset, string value)
        {
            // Get dataBytes
            var byteCount = WatchVariable.TypeSize[watchVar.Type];
            var address   = watchVar.OtherOffset ? offset + watchVar.Address : watchVar.Address;
            var dataBytes = new byte[8];

            stream.ReadRam(address, byteCount, watchVar.AbsoluteAddressing).CopyTo(dataBytes, 0);
            UInt64 oldValue = BitConverter.ToUInt64(dataBytes, 0);
            UInt64 newValue;

            // Handle hex variable
            if (ParsingUtilities.IsHex(value))
            {
                if (!ParsingUtilities.TryParseExtHex(value, out newValue))
                {
                    return(null);
                }
            }
            // Handle floats
            else if (watchVar.Type == typeof(float))
            {
                float newFloatValue;
                if (!float.TryParse(value, out newFloatValue))
                {
                    return(null);
                }

                // Get bytes
                newValue = BitConverter.ToUInt32(BitConverter.GetBytes(newFloatValue), 0);
            }
            else if (watchVar.Type == typeof(double))
            {
                double newFloatValue;
                if (double.TryParse(value, out newFloatValue))
                {
                    return(null);
                }

                // Get bytes
                newValue = BitConverter.ToUInt64(BitConverter.GetBytes(newFloatValue), 0);
            }
            else if (watchVar.Type == typeof(UInt64))
            {
                if (!UInt64.TryParse(value, out newValue))
                {
                    Int64 newValueInt;
                    if (!Int64.TryParse(value, out newValueInt))
                    {
                        return(null);
                    }

                    newValue = (UInt64)newValueInt;
                }
            }
            else
            {
                Int64 tempInt;
                if (!Int64.TryParse(value, out tempInt))
                {
                    return(null);
                }
                newValue = (UInt64)tempInt;
            }

            // Apply mask
            if (watchVar.Mask.HasValue)
            {
                newValue = (newValue & watchVar.Mask.Value) | ((~watchVar.Mask.Value) & oldValue);
            }

            var writeBytes = new byte[byteCount];
            var valueBytes = BitConverter.GetBytes(newValue);

            Array.Copy(valueBytes, 0, writeBytes, 0, byteCount);

            return(writeBytes);
        }
Exemple #30
0
        private void CalculateCoinTrajectories()
        {
            ClearCoinTrajectories();

            double?hSpeedScale          = ParsingUtilities.ParseIntNullable(_textBoxCoinHSpeedScale.Text);
            double?vSpeedScale          = ParsingUtilities.ParseIntNullable(_textBoxCoinVSpeedScale.Text);
            double?vSpeedOffset         = ParsingUtilities.ParseIntNullable(_textBoxCoinVSpeedOffset.Text);
            bool   coinParamOrderParsed = Enum.TryParse(_textBoxCoinParamOrder.Text, out CoinParamOrder coinParamOrder);
            int?   numCoins             = ParsingUtilities.ParseIntNullable(_textBoxCoinNumCoins.Text);

            if (!hSpeedScale.HasValue ||
                !vSpeedScale.HasValue ||
                !vSpeedOffset.HasValue ||
                !coinParamOrderParsed ||
                !numCoins.HasValue)
            {
                DialogUtilities.DisplayMessage(
                    "Could not parse coin param fields.",
                    "Parsing Error");
                return;
            }

            CoinObject coinObject = new CoinObject(
                hSpeedScale: hSpeedScale.Value,
                vSpeedScale: vSpeedScale.Value,
                vSpeedOffset: vSpeedOffset.Value,
                coinParamOrder: coinParamOrder,
                numCoins: numCoins.Value,
                name: "Dummy");

            int?startingRngIndexNullable = ParsingUtilities.ParseIntNullable(
                _textBoxCoinCustomizatonStartingRngIndex.Text);
            int startingRngIndex = startingRngIndexNullable ?? RngIndexer.GetRngIndex();

            int?numDecimalDigitsNullable = ParsingUtilities.ParseIntNullable(
                _textBoxCoinCustomizatonNumDecimalDigits.Text);
            int numDecimalDigits = numDecimalDigitsNullable ?? 3;

            List <int> rngIndexes = Enumerable.Range(0, 65114).ToList();

            foreach (int rngIndex in rngIndexes)
            {
                // rng based values
                ushort rngValue = RngIndexer.GetRngValue(rngIndex);
                int    rngToGo  = MoreMath.NonNegativeModulus(rngIndex - startingRngIndex, 65114);

                // coin trajectory
                List <CoinTrajectory> coinTrajectories = coinObject.CalculateCoinTrajectories(rngIndex);

                // filter the values
                CoinTrajectoryFilter filter = new CoinTrajectoryFilter(
                    ParsingUtilities.ParseDoubleNullable(_textBoxCoinFilterHSpeedMin.Text),
                    ParsingUtilities.ParseDoubleNullable(_textBoxCoinFilterHSpeedMax.Text),
                    ParsingUtilities.ParseDoubleNullable(_textBoxCoinFilterVSpeedMin.Text),
                    ParsingUtilities.ParseDoubleNullable(_textBoxCoinFilterVSpeedMax.Text),
                    ParsingUtilities.ParseDoubleNullable(_textBoxCoinFilterAngleMin.Text),
                    ParsingUtilities.ParseDoubleNullable(_textBoxCoinFilterAngleMax.Text),
                    ParsingUtilities.ParseIntNullable(_textBoxCoinFilterRequiredNumOfQualifiedCoins.Text));
                if (!filter.Qualifies(coinTrajectories))
                {
                    continue;
                }

                if (!_checkBoxCoinCustomizatonDisplayNonQualifiedCoinsOfAQualifiedCoinGroup.Checked)
                {
                    coinTrajectories = coinTrajectories.FindAll(
                        coinTrajectory => filter.Qualifies(coinTrajectory));
                }

                List <double> hSpeedList = coinTrajectories.ConvertAll(
                    coinTrajectory => Math.Round(coinTrajectory.HSpeed, numDecimalDigits));
                List <double> vSpeedList = coinTrajectories.ConvertAll(
                    coinTrajectory => Math.Round(coinTrajectory.VSpeed, numDecimalDigits));
                List <ushort> angleList = coinTrajectories.ConvertAll(
                    coinTrajectory => coinTrajectory.Angle);

                object hSpeedJoined = hSpeedList.Count == 1 ? hSpeedList[0] : (object)String.Join(", ", hSpeedList);
                object vSpeedJoined = vSpeedList.Count == 1 ? vSpeedList[0] : (object)String.Join(", ", vSpeedList);
                object angleJoined  = angleList.Count == 1 ? angleList[0] : (object)String.Join(", ", angleList);

                // add a new row to the table
                _dataGridViewCoin.Rows.Add(
                    rngIndex, rngValue, rngToGo, hSpeedJoined, vSpeedJoined, angleJoined);
            }
        }