public void TestTryGetValue1()
        {
            int val;

            Assert.IsTrue(dict1.TryGetValue(bob, out val));
            Assert.AreEqual(2, val);

            Assert.IsFalse(dict1.TryGetValue(dora, out val));
            Assert.AreEqual(default(int), val);
        }
Example #2
0
        /// <summary>
        /// Gets the value of a variable.
        /// </summary>
        /// <param name="variableName">Name of the variable.</param>
        /// <returns>Value of the variable, <c>null</c> if not found.</returns>
        public ExpressionBase GetVariable(string variableName)
        {
            KeyValuePair <VariableDefinitionExpression, ExpressionBase> variable;

            if (_variables.TryGetValue(variableName, out variable))
            {
                return(variable.Value);
            }

            var parentScope = GetParentScope(this);

            if (parentScope != null)
            {
                return(parentScope.GetVariable(variableName));
            }

            return(null);
        }
Example #3
0
        public ParseErrorExpression Merge(RichPresenceBuilder from)
        {
            if (!String.IsNullOrEmpty(from.DisplayString))
            {
                DisplayString = from.DisplayString;
            }

            _conditionalDisplayStrings.AddRange(from._conditionalDisplayStrings);

            foreach (var kvp in from._valueFields)
            {
                ValueField field;
                if (!_valueFields.TryGetValue(kvp.Key, out field))
                {
                    _valueFields.Add(kvp);
                }
                else if (field.Format != kvp.Value.Format)
                {
                    return(new ParseErrorExpression("Multiple rich_presence_value calls with the same name must have the same format", field.Func));
                }
            }

            foreach (var kvp in from._lookupFields)
            {
                Lookup existing;
                if (!_lookupFields.TryGetValue(kvp.Key, out existing))
                {
                    _lookupFields.Add(kvp);
                }
                else
                {
                    var toMerge = kvp.Value;

                    if (existing.Fallback != toMerge.Fallback)
                    {
                        return(new ParseErrorExpression("Multiple rich_presence_lookup calls with the same name must have the same fallback", toMerge.Fallback ?? existing.Fallback));
                    }

                    if (existing.Entries.Count != toMerge.Entries.Count)
                    {
                        return(new ParseErrorExpression("Multiple rich_presence_lookup calls with the same name must have the same dictionary", toMerge.Func ?? existing.Func));
                    }

                    foreach (var kvp2 in existing.Entries)
                    {
                        string value;
                        if (!toMerge.Entries.TryGetValue(kvp2.Key, out value) || kvp2.Value != value)
                        {
                            return(new ParseErrorExpression("Multiple rich_presence_lookup calls with the same name must have the same dictionary", toMerge.Func ?? existing.Func));
                        }
                    }
                }
            }

            return(null);
        }
Example #4
0
        /// <summary>
        /// Get the color registered for a custom syntax type.
        /// </summary>
        /// <param name="id">The unique identifier of the syntax type.</param>
        /// <returns>The color to use when text is identified as the syntax type.</returns>
        public Color GetCustomColor(int id)
        {
            Color color;

            if (!_customColors.TryGetValue(id, out color))
            {
                color = Colors.Orange;
            }
            return(color);
        }
Example #5
0
        /// <summary>
        /// Gets the brush for a custom syntax type.
        /// </summary>
        /// <param name="id">The unique identifier of the syntax type.</param>
        /// <returns>The brush to use when text is identified as the syntax type.</returns>
        public Brush GetCustomBrush(int id)
        {
            Brush brush;

            if (_customBrushes.TryGetValue(id, out brush))
            {
                return(brush);
            }

            Color color = _properties.GetCustomColor(id);

            brush = new SolidColorBrush(color);
            brush.Freeze();
            _customBrushes[id] = brush;

            return(brush);
        }
Example #6
0
        /// <summary>
        /// Gets the function definition for a function.
        /// </summary>
        /// <param name="functionName">Name of the function.</param>
        /// <returns>Requested <see cref="FunctionDefinitionExpression"/>, <c>null</c> if not found.</returns>
        public FunctionDefinitionExpression GetFunction(string functionName)
        {
            FunctionDefinitionExpression function;

            if (_functions.TryGetValue(functionName, out function))
            {
                return(function);
            }

            var parentScope = GetParentScope(this);

            if (parentScope != null)
            {
                return(parentScope.GetFunction(functionName));
            }

            return(null);
        }
Example #7
0
        private void Dump(Stream outStream)
        {
            MemoryAddresses.Commit();

            using (var stream = new StreamWriter(outStream))
            {
                stream.Write("// ");
                stream.WriteLine(_game.Title);
                stream.Write("// #ID = ");
                stream.WriteLine(String.Format("{0}", _game.GameId));
                bool   needLine      = true;
                bool   hadFunction   = false;
                var    numberFormat  = ServiceRepository.Instance.FindService <ISettings>().HexValues ? NumberFormat.Hexadecimal : NumberFormat.Decimal;
                string addressFormat = "{0:X4}";
                if (_memoryItems.Count > 0 && _memoryItems[_memoryItems.Count - 1].Address > 0xFFFF)
                {
                    addressFormat = "{0:X6}";
                }

                bool first;
                var  dumpNotes           = SelectedNoteDump;
                var  filter              = SelectedCodeNotesFilter;
                uint previousNoteAddress = UInt32.MaxValue;
                foreach (var memoryItem in _memoryItems)
                {
                    if (filter == CodeNoteFilter.ForSelectedAchievements)
                    {
                        if (MemoryAddresses.GetRow(memoryItem) == null)
                        {
                            continue;
                        }
                    }

                    string notes = null;
                    if (dumpNotes != NoteDump.None)
                    {
                        if (_game.Notes.TryGetValue((int)memoryItem.Address, out notes))
                        {
                            if (String.IsNullOrEmpty(memoryItem.FunctionName))
                            {
                                if (dumpNotes == NoteDump.OnlyForDefinedMethods)
                                {
                                    continue;
                                }

                                if (memoryItem.Address == previousNoteAddress)
                                {
                                    continue;
                                }
                            }
                        }
                    }

                    if (!String.IsNullOrEmpty(notes))
                    {
                        notes = notes.Trim();
                        if (notes.Length > 0)
                        {
                            if (needLine || hadFunction || !String.IsNullOrEmpty(memoryItem.FunctionName))
                            {
                                needLine = false;
                                stream.WriteLine();
                            }

                            var lines = notes.Split('\n');
                            stream.Write("// $");

                            previousNoteAddress = memoryItem.Address;
                            var address = String.Format(addressFormat, memoryItem.Address);
                            stream.Write(address);
                            stream.Write(": ");
                            stream.WriteLine(lines[0].Trim());

                            for (int i = 1; i < lines.Length; i++)
                            {
                                stream.Write("//        ");
                                if (address.Length > 4)
                                {
                                    stream.Write("   ".ToCharArray(), 0, address.Length - 4);
                                }
                                stream.WriteLine(lines[i].Trim());
                            }
                        }
                    }

                    if (!String.IsNullOrEmpty(memoryItem.FunctionName))
                    {
                        if (needLine)
                        {
                            needLine = false;
                            stream.WriteLine();
                        }
                        hadFunction = true;

                        stream.Write("function ");
                        stream.Write(memoryItem.FunctionName);
                        stream.Write("() => ");
                        var memoryReference = Field.GetMemoryReference(memoryItem.Address, memoryItem.Size);
                        stream.WriteLine(memoryReference);
                    }
                    else
                    {
                        hadFunction = false;
                    }
                }

                foreach (var dumpAchievement in _achievements)
                {
                    if (!dumpAchievement.IsSelected)
                    {
                        continue;
                    }

                    var achievement = _game.Editors.FirstOrDefault(a => a.Id == dumpAchievement.Id) as GeneratedAchievementViewModel;
                    if (achievement == null)
                    {
                        continue;
                    }

                    stream.WriteLine();

                    foreach (var ticket in dumpAchievement.OpenTickets)
                    {
                        string notes;
                        if (_ticketNotes.TryGetValue(ticket, out notes))
                        {
                            var lines = notes.Replace("<br/>", "\n").Split('\n');

                            stream.Write("// Ticket ");
                            stream.Write(ticket);
                            stream.Write(": ");

                            first = true;
                            const int MaxLength = 103; // 120 - "// Ticket XXXXX: ".Length
                            for (int i = 0; i < lines.Length; i++)
                            {
                                if (first)
                                {
                                    first = false;
                                }
                                else
                                {
                                    stream.Write("//               ");
                                }

                                var line = lines[i].Trim();
                                while (line.Length > MaxLength)
                                {
                                    var index = line.LastIndexOf(' ', MaxLength - 1);
                                    var front = line.Substring(0, index).Trim();
                                    stream.WriteLine(front);
                                    line = line.Substring(index + 1).Trim();

                                    if (line.Length > 0)
                                    {
                                        stream.Write("//               ");
                                    }
                                }

                                if (line.Length > 0)
                                {
                                    stream.WriteLine(line);
                                }
                            }

                            if (first)
                            {
                                stream.WriteLine();
                            }
                        }
                    }

                    stream.WriteLine("achievement(");

                    var achievementViewModel = (achievement.Core.Achievement != null) ? achievement.Core : achievement.Unofficial;
                    var achievementData      = achievementViewModel.Achievement;

                    stream.Write("    title = \"");
                    stream.Write(EscapeString(achievementData.Title));
                    stream.Write("\", description = \"");
                    stream.Write(EscapeString(achievementData.Description));
                    stream.Write("\", points = ");
                    stream.Write(achievementData.Points);
                    stream.WriteLine(",");

                    stream.Write("    id = ");
                    stream.Write(achievementData.Id);
                    stream.Write(", badge = \"");
                    stream.Write(achievementData.BadgeName);
                    stream.Write("\", published = \"");
                    stream.Write(achievementData.Published);
                    stream.Write("\", modified = \"");
                    stream.Write(achievementData.LastModified);
                    stream.WriteLine("\",");

                    var groupEnumerator = achievementViewModel.RequirementGroups.GetEnumerator();
                    groupEnumerator.MoveNext();
                    stream.Write("    trigger = ");
                    DumpPublishedRequirements(stream, dumpAchievement, groupEnumerator.Current, numberFormat);
                    first = true;
                    while (groupEnumerator.MoveNext())
                    {
                        if (first)
                        {
                            stream.WriteLine(" &&");
                            stream.Write("              ((");
                            first = false;
                        }
                        else
                        {
                            stream.WriteLine(" ||");
                            stream.Write("               (");
                        }

                        DumpPublishedRequirements(stream, dumpAchievement, groupEnumerator.Current, numberFormat);
                        stream.Write(")");
                    }
                    if (!first)
                    {
                        stream.Write(')');
                    }

                    stream.WriteLine();

                    stream.WriteLine(")");
                }
            }
        }
Example #8
0
        public RichPresenceViewModel(GameViewModel owner, string richPresence)
        {
            Title = "Rich Presence";

            _richPresence = richPresence ?? string.Empty;
            var genLines = _richPresence.Trim().Length > 0 ? _richPresence.Replace("\r\n", "\n").Split('\n') : new string[0];

            string[] localLines = new string[0];

            if (String.IsNullOrEmpty(owner.RACacheDirectory))
            {
                UpdateLocalCommand = DisabledCommand.Instance;
            }
            else
            {
                UpdateLocalCommand = new DelegateCommand(UpdateLocal);

                _richFile = Path.Combine(owner.RACacheDirectory, owner.GameId + "-Rich.txt");
                if (File.Exists(_richFile))
                {
                    var coreRichPresence = File.ReadAllText(_richFile);
                    RichPresenceLength = coreRichPresence.Length;
                    if (RichPresenceLength > 0)
                    {
                        localLines = coreRichPresence.Replace("\r\n", "\n").Split('\n');
                    }
                }
            }

            var  lines = new List <RichPresenceLine>();
            int  genIndex = 0, localIndex = 0;
            bool isModified = false;

            var genTags = new TinyDictionary <string, int>();

            for (int i = 0; i < genLines.Length; i++)
            {
                var line = genLines[i];
                if (line.StartsWith("Format:") || line.StartsWith("Lookup:") || line.StartsWith("Display:"))
                {
                    genTags[line] = i;
                }
            }

            var localTags = new TinyDictionary <string, int>();

            for (int i = 0; i < localLines.Length; i++)
            {
                var line = localLines[i];
                if (line.StartsWith("Format:") || line.StartsWith("Lookup:") || line.StartsWith("Display:"))
                {
                    localTags[line] = i;
                }
            }

            _hasGenerated = genLines.Length > 0;
            _hasLocal     = localLines.Length > 0;

            while (genIndex < genLines.Length && localIndex < localLines.Length)
            {
                if (genLines[genIndex] == localLines[localIndex])
                {
                    // matching lines, advance both
                    lines.Add(new RichPresenceLine(localLines[localIndex++], genLines[genIndex++]));
                    continue;
                }

                isModified = true;

                if (genLines[genIndex].Length == 0)
                {
                    // blank generated line, advance core
                    lines.Add(new RichPresenceLine(localLines[localIndex++], genLines[genIndex]));
                    continue;
                }

                if (localLines[localIndex].Length == 0)
                {
                    // blank core line, advance generated
                    lines.Add(new RichPresenceLine(localLines[localIndex], genLines[genIndex++]));
                    continue;
                }

                // if we're starting a lookup or value, try to line them up
                int genTagLine, localTagLine;
                if (!genTags.TryGetValue(localLines[localIndex], out genTagLine))
                {
                    genTagLine = -1;
                }
                if (!localTags.TryGetValue(genLines[genIndex], out localTagLine))
                {
                    localTagLine = -1;
                }

                if (genTagLine != -1 && localTagLine != -1)
                {
                    if (genTagLine > localTagLine)
                    {
                        genTagLine = -1;
                    }
                    else
                    {
                        localTagLine = -1;
                    }
                }

                if (genTagLine != -1)
                {
                    do
                    {
                        lines.Add(new RichPresenceLine("", genLines[genIndex++]));
                    } while (genIndex < genLines.Length && genLines[genIndex].Length > 0);

                    if (genIndex < genLines.Length)
                    {
                        lines.Add(new RichPresenceLine("", genLines[genIndex++]));
                    }
                    continue;
                }

                if (localTagLine != -1)
                {
                    do
                    {
                        lines.Add(new RichPresenceLine(localLines[localIndex++], ""));
                    } while (localIndex < localLines.Length && localLines[localIndex].Length > 0);

                    if (localIndex < localLines.Length)
                    {
                        lines.Add(new RichPresenceLine(localLines[localIndex++], ""));
                    }
                    continue;
                }

                // non-matching lines, scan ahead to find a match
                bool found = false;
                for (int temp = genIndex + 1; temp < genLines.Length; temp++)
                {
                    if (genLines[temp].Length == 0)
                    {
                        break;
                    }

                    if (genLines[temp] == localLines[localIndex])
                    {
                        while (genIndex < temp)
                        {
                            lines.Add(new RichPresenceLine("", genLines[genIndex++]));
                        }

                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    for (int temp = localIndex + 1; temp < localLines.Length; temp++)
                    {
                        if (localLines[temp].Length == 0)
                        {
                            break;
                        }

                        if (localLines[temp] == genLines[genIndex])
                        {
                            while (localIndex < temp)
                            {
                                lines.Add(new RichPresenceLine(localLines[localIndex++], ""));
                            }

                            found = true;
                            break;
                        }
                    }
                }

                // if a match was found, the next iteration will match them. if one wasn't found, advance both.
                if (!found)
                {
                    lines.Add(new RichPresenceLine(localLines[localIndex++], genLines[genIndex++]));
                }
            }

            if (!_hasGenerated)
            {
                foreach (var line in localLines)
                {
                    lines.Add(new RichPresenceLine(line));
                }

                GeneratedSource = "Local (Not Generated)";
                CompareSource   = String.Empty;

                ModificationMessage = null;
                CompareState        = GeneratedCompareState.None;
                CanUpdate           = false;
            }
            else if (isModified || genIndex != genLines.Length || localIndex != localLines.Length)
            {
                while (genIndex < genLines.Length)
                {
                    lines.Add(new RichPresenceLine("", genLines[genIndex++]));
                }
                while (localIndex < localLines.Length)
                {
                    lines.Add(new RichPresenceLine(localLines[localIndex++], ""));
                }

                if (!_hasLocal)
                {
                    GeneratedSource = "Generated (Not in Local)";
                    CompareSource   = String.Empty;
                }

                RichPresenceLength  = _richPresence.Length;
                ModificationMessage = _hasLocal ? "Local value differs from generated value" : "Local value does not exist";
                CompareState        = GeneratedCompareState.LocalDiffers;
                CanUpdate           = true;
            }
            else
            {
                GeneratedSource = "Generated (Same as Local)";
                CompareSource   = String.Empty;

                ModificationMessage = null;
                CanUpdate           = false;

                lines.Clear();
                foreach (var line in genLines)
                {
                    lines.Add(new RichPresenceLine(line));
                }
            }

            Lines = lines;

            if (_hasGenerated)
            {
                CopyToClipboardCommand = new DelegateCommand(() =>
                {
                    ServiceRepository.Instance.FindService <IClipboardService>().SetData(_richPresence);

                    if (_richPresence.Length > RichPresenceMaxLength)
                    {
                        MessageBoxViewModel.ShowMessage("Rich Presence exceeds maximum length of " + RichPresenceMaxLength + " characters (" + _richPresence.Length + ")");
                    }
                });
            }
        }
Example #9
0
        private bool CreateRow(ModelBase model, IDatabase database, string tableName, IEnumerable <int> tablePropertyKeys, ModelProperty joinProperty, string joinFieldName)
        {
            bool onlyDefaults      = (joinFieldName != null);
            var  properties        = new List <ModelProperty>();
            var  refreshProperties = new List <ModelProperty>();

            foreach (var propertyKey in tablePropertyKeys)
            {
                var property      = ModelProperty.GetPropertyForKey(propertyKey);
                var fieldMetadata = GetFieldMetadata(property);
                if ((fieldMetadata.Attributes & InternalFieldAttributes.GeneratedByCreate) == 0)
                {
                    if (onlyDefaults && model.GetValue(property) != property.DefaultValue)
                    {
                        onlyDefaults = false;
                    }

                    properties.Add(property);
                }

                if ((fieldMetadata.Attributes & InternalFieldAttributes.RefreshAfterCommit) != 0)
                {
                    refreshProperties.Add(property);
                }
            }

            if (properties.Count == 0 || onlyDefaults)
            {
                return(true);
            }

            var builder = new StringBuilder();

            builder.Append("INSERT INTO ");
            builder.Append(tableName);
            builder.Append(" (");

            if (joinFieldName != null)
            {
                builder.Append('[');
                builder.Append(GetFieldName(joinFieldName));
                builder.Append("], ");
            }

            foreach (var property in properties)
            {
                var fieldMetadata = GetFieldMetadata(property);
                var fieldName     = GetFieldName(fieldMetadata.FieldName);
                builder.Append('[');
                builder.Append(fieldName);
                builder.Append("], ");
            }

            builder.Length -= 2;
            builder.Append(") VALUES (");

            if (joinFieldName != null)
            {
                var fieldMetadata = GetFieldMetadata(joinProperty);
                var value         = model.GetValue(joinProperty);
                value = CoerceValueToDatabase(joinProperty, fieldMetadata, value);
                AppendQueryValue(builder, value, GetFieldMetadata(joinProperty), database);
                builder.Append(", ");
            }

            var values = new TinyDictionary <FieldMetadata, object>();

            foreach (var property in properties)
            {
                var fieldMetadata = GetFieldMetadata(property);
                var value         = model.GetValue(property);

                object previousValue;
                if (values.TryGetValue(fieldMetadata, out previousValue))
                {
                    if (!Object.Equals(value, previousValue))
                    {
                        throw new InvalidOperationException("Cannot set " + fieldMetadata.FieldName + " to '" + previousValue + "' and '" + value + "'");
                    }
                }
                else
                {
                    value = CoerceValueToDatabase(property, fieldMetadata, value);
                    values[fieldMetadata] = value;

                    AppendQueryValue(builder, value, fieldMetadata, database);
                    builder.Append(", ");
                }
            }

            builder.Length -= 2;
            builder.Append(')');

            try
            {
                if (database.ExecuteCommand(builder.ToString()) == 0)
                {
                    return(false);
                }

                if (refreshProperties.Count > 0)
                {
                    RefreshAfterCommit(model, database, refreshProperties, properties);
                }

                return(true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message + ": " + builder.ToString());
                return(false);
            }
        }