public ParseErrorExpression AddLookupField(ExpressionBase func, string name, DictionaryExpression dict, StringConstantExpression fallback) { var tinyDict = new TinyDictionary <int, string>(); foreach (var entry in dict.Entries) { var key = entry.Key as IntegerConstantExpression; if (key == null) { return(new ParseErrorExpression("key is not an integer", entry.Key)); } var value = entry.Value as StringConstantExpression; if (value == null) { return(new ParseErrorExpression("value is not a string", entry.Value)); } tinyDict[key.Value] = value.Value; } _lookupFields[name] = new Lookup { Func = func, Entries = tinyDict, Fallback = fallback }; return(null); }
/// <summary> /// Reads this ini file. /// </summary> /// <returns>Dictionary of key/value pairs for entries read from the .ini file.</returns> /// <exception cref="FileNotFoundException">The specified file was not found.</exception> public IDictionary <string, string> Read() { if (!File.Exists(_iniPath)) { throw new FileNotFoundException(_iniPath + " not found"); } var values = new TinyDictionary <string, string>(); using (var reader = new StreamReader(File.Open(_iniPath, FileMode.Open, FileAccess.Read))) { while (!reader.EndOfStream) { var line = reader.ReadLine(); var lineToken = new Token(line, 0, line.Length).Trim(); int index = lineToken.IndexOf('#'); if (index >= 0) { lineToken = lineToken.SubToken(0, index).TrimRight(); } index = lineToken.IndexOf('='); if (index > 0) { var key = lineToken.SubToken(0, index).TrimRight(); var value = lineToken.SubToken(index + 1).TrimLeft(); values[key.ToString()] = value.ToString(); } } } return(values); }
/// <summary> /// Determines the allowed vehicle types that may approach the given node from the given segment (lane-wise). /// </summary> /// <param name="segmentId"></param> /// <param name="nodeId"></param> /// <returns></returns> public IDictionary<byte, ExtVehicleType> GetAllowedVehicleTypesAsDict(ushort segmentId, ushort nodeId, VehicleRestrictionsMode busLaneMode) { IDictionary<byte, ExtVehicleType> ret = new TinyDictionary<byte, ExtVehicleType>(); NetManager netManager = Singleton<NetManager>.instance; if (segmentId == 0 || (netManager.m_segments.m_buffer[segmentId].m_flags & NetSegment.Flags.Created) == NetSegment.Flags.None || nodeId == 0 || (netManager.m_nodes.m_buffer[nodeId].m_flags & NetNode.Flags.Created) == NetNode.Flags.None) { return ret; } var dir = NetInfo.Direction.Forward; var dir2 = ((netManager.m_segments.m_buffer[segmentId].m_flags & NetSegment.Flags.Invert) == NetSegment.Flags.None) ? dir : NetInfo.InvertDirection(dir); NetInfo segmentInfo = netManager.m_segments.m_buffer[segmentId].Info; uint curLaneId = netManager.m_segments.m_buffer[segmentId].m_lanes; int numLanes = segmentInfo.m_lanes.Length; uint laneIndex = 0; while (laneIndex < numLanes && curLaneId != 0u) { NetInfo.Lane laneInfo = segmentInfo.m_lanes[laneIndex]; if (laneInfo.m_laneType == NetInfo.LaneType.Vehicle || laneInfo.m_laneType == NetInfo.LaneType.TransportVehicle) { if (laneInfo.m_vehicleType != VehicleInfo.VehicleType.None) { ushort toNodeId = (laneInfo.m_finalDirection & dir2) != NetInfo.Direction.None ? netManager.m_segments.m_buffer[segmentId].m_endNode : netManager.m_segments.m_buffer[segmentId].m_startNode; if ((laneInfo.m_finalDirection & NetInfo.Direction.Both) == NetInfo.Direction.Both || toNodeId == nodeId) { ExtVehicleType vehicleTypes = GetAllowedVehicleTypes(segmentId, segmentInfo, laneIndex, laneInfo, busLaneMode); ret[(byte)laneIndex] = vehicleTypes; } } } curLaneId = netManager.m_lanes.m_buffer[curLaneId].m_nextLane; ++laneIndex; } return ret; }
const int BRAND_ISOM = 0x69736F6D; // isom /// <summary> /// Initializes a new instance of the <see cref="Mp4Reader"/> class. /// </summary> /// <param name="filePath">The path to the MP4 file.</param> /// <exception cref="ArgumentException"> /// The file at <paramref name="filePath"/> is not a valid MP4 file or not a supported MP4 version. /// </exception> public Mp4Reader(string filePath) { using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read)) { var reader = new BinaryReader(stream); uint next = ReadUInt32(reader); uint identifier = ReadUInt32(reader); if (identifier != CONTAINER_IDENTIFIER) { throw new ArgumentException("Stream does not appear to be an MP4 container", "stream"); } uint brand = ReadUInt32(reader); if (brand != BRAND_MP42 && brand != BRAND_ISOM) { throw new ArgumentException("Stream is not an MP4.2 container", "stream"); } reader.BaseStream.Position = next; _blocks = new List <Mp4Block>(); GetAllBlocks(reader); _tags = new TinyDictionary <Mp4Tag, string>(); GetTags(reader); } }
private FunctionDefinitionExpression() : base(ExpressionType.FunctionDefinition) { Parameters = new List <VariableDefinitionExpression>(); Expressions = new List <ExpressionBase>(); DefaultParameters = new TinyDictionary <string, ExpressionBase>(); }
public void TestNested() { dict4 = new TinyDictionary <ushort, IDictionary <ushort, ArrowDirection> >(); IDictionary <ushort, ArrowDirection> innerDict1 = new TinyDictionary <ushort, ArrowDirection>(); dict4.Add(1270, innerDict1); innerDict1.Add(1270, ArrowDirection.Turn); innerDict1.Add(14929, ArrowDirection.Forward); innerDict1.Add(26395, ArrowDirection.Left); IDictionary <ushort, ArrowDirection> innerDict2 = new TinyDictionary <ushort, ArrowDirection>(); dict4.Add(14929, innerDict2); innerDict2.Add(1270, ArrowDirection.Forward); innerDict2.Add(14929, ArrowDirection.Turn); innerDict2.Add(26395, ArrowDirection.Right); IDictionary <ushort, ArrowDirection> innerDict3 = new TinyDictionary <ushort, ArrowDirection>(); dict4.Add(26395, innerDict3); innerDict3.Add(1270, ArrowDirection.Right); innerDict3.Add(14929, ArrowDirection.Left); innerDict3.Add(26395, ArrowDirection.Turn); Assert.AreEqual(3, dict4.Count); Assert.IsTrue(dict4.ContainsKey(1270)); Assert.IsTrue(dict4.ContainsKey(14929)); Assert.IsTrue(dict4.ContainsKey(26395)); Assert.AreEqual(3, dict4[1270].Count); Assert.AreEqual(3, dict4[14929].Count); Assert.AreEqual(3, dict4[26395].Count); Assert.IsTrue(dict4[1270].ContainsKey(1270)); Assert.IsTrue(dict4[1270].ContainsKey(14929)); Assert.IsTrue(dict4[1270].ContainsKey(26395)); Assert.IsTrue(dict4[14929].ContainsKey(1270)); Assert.IsTrue(dict4[14929].ContainsKey(14929)); Assert.IsTrue(dict4[14929].ContainsKey(26395)); Assert.IsTrue(dict4[26395].ContainsKey(1270)); Assert.IsTrue(dict4[26395].ContainsKey(14929)); Assert.IsTrue(dict4[26395].ContainsKey(26395)); Assert.AreEqual(ArrowDirection.Turn, dict4[1270][1270]); Assert.AreEqual(ArrowDirection.Forward, dict4[1270][14929]); Assert.AreEqual(ArrowDirection.Left, dict4[1270][26395]); Assert.AreEqual(ArrowDirection.Forward, dict4[14929][1270]); Assert.AreEqual(ArrowDirection.Turn, dict4[14929][14929]); Assert.AreEqual(ArrowDirection.Right, dict4[14929][26395]); Assert.AreEqual(ArrowDirection.Right, dict4[26395][1270]); Assert.AreEqual(ArrowDirection.Left, dict4[26395][14929]); Assert.AreEqual(ArrowDirection.Turn, dict4[26395][26395]); }
protected FunctionDefinitionExpression(VariableDefinitionExpression name) : base(ExpressionType.FunctionDefinition) { Name = name; Parameters = new List <VariableDefinitionExpression>(); Expressions = new List <ExpressionBase>(); DefaultParameters = new TinyDictionary <string, ExpressionBase>(); }
public GameViewModel(int gameId, string title) { GameId = gameId; Title = title; Script = new ScriptViewModel(this); SelectedEditor = Script; Notes = new TinyDictionary <int, string>(); GoToSourceCommand = new DelegateCommand <int>(GoToSource); _logger = ServiceRepository.Instance.FindService <ILogService>().GetLogger("RATools"); }
private void RebuildVehicleNumDicts(ref NetNode node) { numVehiclesMovingToSegmentId = new TinyDictionary <ushort, uint> [numLanes]; numVehiclesGoingToSegmentId = new TinyDictionary <ushort, uint> [numLanes]; Constants.ServiceFactory.NetService.IterateSegmentLanes( SegmentId, (uint laneId, ref NetLane lane, NetInfo.Lane laneInfo, ushort segmentId, ref NetSegment segment, byte laneIndex) => { IDictionary <ushort, uint> numVehicleMoving = new TinyDictionary <ushort, uint>(); IDictionary <ushort, uint> numVehicleGoing = new TinyDictionary <ushort, uint>(); numVehiclesMovingToSegmentId[laneIndex] = numVehicleMoving; numVehiclesGoingToSegmentId[laneIndex] = numVehicleGoing; return(true); }); IExtSegmentEndManager segEndMan = Constants.ManagerFactory.ExtSegmentEndManager; for (int i = 0; i < 8; ++i) { ushort segId = node.GetSegment(i); if (segId == 0) { continue; } int index0 = segEndMan.GetIndex( segId, (bool)Constants.ServiceFactory.NetService.IsStartNode(segId, NodeId)); if (!segEndMan.ExtSegmentEnds[index0].outgoing) { continue; } foreach (TinyDictionary <ushort, uint> numVehiclesMovingToSegId in numVehiclesMovingToSegmentId) { numVehiclesMovingToSegId[segId] = 0; } foreach (TinyDictionary <ushort, uint> numVehiclesGoingToSegId in numVehiclesGoingToSegmentId) { numVehiclesGoingToSegId[segId] = 0; } } } // end RebuildVehicleNumDicts
protected GameViewModel(int gameId, string title, ILogger logger, IFileSystemService fileSystemService) { /* unit tests call this constructor directly and will provide their own Script object and don't need Resources */ GameId = gameId; Title = title; Notes = new TinyDictionary <int, string>(); GoToSourceCommand = new DelegateCommand <int>(GoToSource); _publishedAchievements = new List <Achievement>(); _publishedLeaderboards = new List <Leaderboard>(); _logger = logger; _fileSystemService = fileSystemService; }
public NewScriptDialogViewModel() { DialogTitle = "New Script"; CanClose = true; SearchCommand = new DelegateCommand(Search); CheckAllCommand = new DelegateCommand(CheckAll); UncheckAllCommand = new DelegateCommand(UncheckAll); CheckWithTicketsCommand = new DelegateCommand(CheckWithTickets); GameId = new IntegerFieldViewModel("Game _ID", 1, 999999); _achievements = new ObservableCollection <DumpAchievementItem>(); _memoryItems = new List <MemoryItem>(); _ticketNotes = new TinyDictionary <int, string>(); CodeNoteFilters = new[] { new CodeNoteFilterLookupItem(CodeNoteFilter.All, "All"), new CodeNoteFilterLookupItem(CodeNoteFilter.ForSelectedAchievements, "For Selected Achievements"), }; NoteDumps = new[] { new NoteDumpLookupItem(NoteDump.None, "None"), new NoteDumpLookupItem(NoteDump.All, "All"), new NoteDumpLookupItem(NoteDump.OnlyForDefinedMethods, "Only for Functions"), }; MemoryAddresses = new GridViewModel(); MemoryAddresses.Columns.Add(new DisplayTextColumnDefinition("Size", MemoryItem.SizeProperty, new DelegateConverter(a => Field.GetSizeFunction((FieldSize)a), null)) { Width = 48 }); MemoryAddresses.Columns.Add(new DisplayTextColumnDefinition("Address", MemoryItem.AddressProperty, new DelegateConverter(a => String.Format("0x{0:X6}", a), null)) { Width = 56 }); MemoryAddresses.Columns.Add(new TextColumnDefinition("Function Name", MemoryItem.FunctionNameProperty, new StringFieldMetadata("Function Name", 40, StringFieldAttributes.Required)) { Width = 120 }); MemoryAddresses.Columns.Add(new DisplayTextColumnDefinition("Notes", MemoryItem.NotesProperty)); }
public void InitializeTest() { dict0 = new TinyDictionary <byte, byte>(); dict1 = new TinyDictionary <string, int>(); dict1.Add(alice, 1); dict1.Add(bob, 2); dict1.Add(cedric, 3); dict2 = new TinyDictionary <string, IList <string> >(); dict2.Add(bob, bobsNicknames); dict2.Add(cedric, cedricsNicknames); dict2.Add(dora, dorasNicknames); dict2.Add(alice, alicesNicknames); dict3 = new TinyDictionary <ICollection <string>, bool>(); dict3.Add(girls, true); dict3.Add(boys, false); }
private void UpdateMetadataInPlace(int ilstIndex, int freeIndex) { using (var stream = File.Open(_path, FileMode.Open, FileAccess.ReadWrite)) { var writer = new BinaryWriter(stream); var exTags = new TinyDictionary <string, string>(); // update the tags stream.Seek(_blocks[ilstIndex].Address + 8, SeekOrigin.Begin); WriteTags(writer, exTags); // update the meta pointers var writerPosition = stream.Position; UpdateBlockSize(writer, "moov.udta.meta.ilst", writerPosition); UpdateBlockSize(writer, "moov.udta.meta", writerPosition); // update the WM tags stream.Position = writerPosition; WriteWmTags(writer); // update the ex tags WriteExTags(writer, exTags); writerPosition = stream.Position; // update the free block size and position var freeBlock = _blocks[freeIndex]; freeBlock.Size = freeBlock.Address + freeBlock.Size - writerPosition; freeBlock.Address = writerPosition; _blocks[ilstIndex + 1] = freeBlock; WriteUInt32(writer, (uint)freeBlock.Size); WriteUInt32(writer, FREE_TAG); UpdateBlockSize(writer, "moov.udta", writerPosition); UpdateBlockSize(writer, "moov", writerPosition); // adjust the blocks for the new file var blockReader = new BinaryReader(stream); blockReader.BaseStream.Seek(_blocks[0].Address, SeekOrigin.Begin); GetAllBlocks(blockReader); } }
/// <summary> /// Initializes a new instance of the <see cref="EditorResources"/> class. /// </summary> /// <param name="properties">The <see cref="EditorProperties"/> to wrap.</param> public EditorResources(EditorProperties properties) { _properties = properties; _properties.CustomColorChanged += properties_CustomColorChanged; Background = new BrushResource(properties, EditorProperties.BackgroundProperty); Foreground = new BrushResource(properties, EditorProperties.ForegroundProperty); Selection = new BrushResource(properties, EditorProperties.SelectionProperty); LineNumber = new BrushResource(properties, EditorProperties.LineNumberProperty); FontName = properties.FontName; FontSize = properties.FontSize; _customBrushes = new TinyDictionary <int, Brush>(); var formattedText = new FormattedText("0", CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface(FontName), FontSize, Brushes.Black, VisualTreeHelper.GetDpi(new Button()).PixelsPerDip); CharacterWidth = formattedText.Width; CharacterHeight = (int)(formattedText.Height + 0.75); }
public void InitializeTest() { dict0 = new TinyDictionary <byte, byte>(); dict1 = new TinyDictionary <string, int> { { alice, 1 }, { bob, 2 }, { cedric, 3 }, }; dict2 = new TinyDictionary <string, IList <string> > { { bob, bobsNicknames }, { cedric, cedricsNicknames }, { dora, dorasNicknames }, { alice, alicesNicknames }, }; dict3 = new TinyDictionary <ICollection <string>, bool> { { girls, true }, { boys, false }, }; }
public void Update() { Constants.ServiceFactory.NetService.ProcessSegment(SegmentId, delegate(ushort segmentId, ref NetSegment segment) { StartNode = segment.m_startNode == NodeId; numLanes = segment.Info.m_lanes.Length; return(true); }); SegmentGeometry segGeo = SegmentGeometry.Get(SegmentId); if (segGeo == null) { Log.Error($"SegmentEnd.Update: No geometry information available for segment {SegmentId}"); return; } ushort[] outgoingSegmentIds = SegmentGeometry.Get(SegmentId).GetOutgoingSegments(StartNode); numVehiclesMovingToSegmentId = new TinyDictionary <ushort, uint> [numLanes]; numVehiclesGoingToSegmentId = new TinyDictionary <ushort, uint> [numLanes]; Constants.ServiceFactory.NetService.IterateSegmentLanes(SegmentId, delegate(uint laneId, ref NetLane lane, NetInfo.Lane laneInfo, ushort segmentId, ref NetSegment segment, byte laneIndex) { IDictionary <ushort, uint> numVehicleMoving = new TinyDictionary <ushort, uint>(); IDictionary <ushort, uint> numVehicleGoing = new TinyDictionary <ushort, uint>(); numVehiclesMovingToSegmentId[laneIndex] = numVehicleMoving; numVehiclesGoingToSegmentId[laneIndex] = numVehicleGoing; foreach (ushort otherSegmentId in outgoingSegmentIds) { numVehicleMoving[otherSegmentId] = 0; numVehicleGoing[otherSegmentId] = 0; } numVehicleMoving[SegmentId] = 0; numVehicleGoing[SegmentId] = 0; return(true); }); }
internal ParseErrorExpression AddLookupField(string name, DictionaryExpression dict) { var tinyDict = new TinyDictionary <int, string>(); foreach (var entry in dict.Entries) { var key = entry.Key as IntegerConstantExpression; if (key == null) { return(new ParseErrorExpression("key is not an integer", entry.Key)); } var value = entry.Value as StringConstantExpression; if (value == null) { return(new ParseErrorExpression("value is not a string", entry.Value)); } tinyDict[key.Value] = value.Value; } AddLookupField(name, tinyDict); return(null); }
/// <summary> /// Initializes a new instance of the <see cref="EditorProperties"/> class. /// </summary> public EditorProperties() { _customColors = new TinyDictionary <int, Color>(); }
/// <summary> /// Initializes a new instance of the <see cref="GraphQuery"/> class. /// </summary> /// <param name="objectType">Name of the object being queried.</param> public GraphQuery(string objectType) { ObjectType = objectType; Filters = new TinyDictionary <string, string>(); Fields = GraphQueryField.EmptyFieldArray; }
public UserStats() { Achievements = new TinyDictionary <int, DateTime>(); }
private void UpdateMetadataInNewFile(int ilstIndex, int freeIndex, Action <int> progressHandler) { var copyPath = _path.Substring(0, _path.Length - 4) + ".tmp" + _path.Substring(_path.Length - 4); using (var readStream = File.Open(_path, FileMode.Open, FileAccess.Read)) { var reader = new BinaryReader(readStream); using (var writeStream = File.Open(copyPath, FileMode.Create, FileAccess.ReadWrite)) { var writer = new BinaryWriter(writeStream); var exTags = new TinyDictionary <string, string>(); // copy everything up to the ilist block header Copy(reader, writer, _blocks[ilstIndex].Address + 8, progressHandler); // generate a new ilist block WriteTags(writer, exTags); // update all the meta pointers var writePosition = writeStream.Position; UpdateBlockSize(writer, "moov.udta.meta.ilst", writePosition); UpdateBlockSize(writer, "moov.udta.meta", writePosition); // update the WM tags writeStream.Position = writePosition; WriteWmTags(writer); // update the ex tags WriteExTags(writer, exTags); // update the outer container pointers writePosition = writeStream.Position; UpdateBlockSize(writer, "moov.udta", writePosition); UpdateBlockSize(writer, "moov", writePosition); writer.BaseStream.Position = writePosition; // generate a new free block in the writer const uint freeBlockSize = 520; WriteUInt32(writer, freeBlockSize); WriteUInt32(writer, FREE_TAG); writer.Write(new byte[freeBlockSize - 8]); // adjust for the new free block var additionalSpaceUsed = writePosition - _blocks[freeIndex].Address + freeBlockSize; writePosition = writer.BaseStream.Position; // if the block following the ilst block is a free block, discard it in favor of // our new one. otherwise, insert our new one in the blocks collection var readPosition = _blocks[freeIndex].Address; if (_blocks[freeIndex].Tag == "free") { additionalSpaceUsed -= _blocks[freeIndex].Size; readPosition += _blocks[freeIndex].Size; } // update all the pointers in the stco (sample table chunk offset) // there can be multiple tracks, so look for all stco's. foreach (var block in _blocks) { if (block.Tag == "moov.trak.mdia.minf.stbl.stco") { writer.BaseStream.Position = block.Address + 16; reader.BaseStream.Position = block.Address + 12; uint entries = ReadUInt32(reader); for (int i = 0; i < entries; i++) { uint offset = ReadUInt32(reader); offset += (uint)additionalSpaceUsed; WriteUInt32(writer, offset); } } } // copy the remaining portion of the file writer.BaseStream.Position = writePosition; reader.BaseStream.Position = readPosition; Copy(reader, writer, reader.BaseStream.Length - reader.BaseStream.Position, progressHandler); // adjust the blocks for the new file var blockReader = new BinaryReader(writeStream); blockReader.BaseStream.Seek(_blocks[0].Address, SeekOrigin.Begin); GetAllBlocks(blockReader); } } // replace the existing file with the new file File.Delete(_path); File.Move(copyPath, _path); // reset the original tags collection _originalTags.Clear(); foreach (var kvp in Tags) { _originalTags[kvp.Key] = kvp.Value; } }
public RichPresenceBuilder() { _valueFields = new TinyDictionary <string, ValueField>(); _lookupFields = new TinyDictionary <string, Lookup>(); _conditionalDisplayStrings = new List <string>(); }
public string GetFormattedErrorMessage(Tokenizer tokenizer) { var neededLines = new List <int>(); var error = Error; while (error != null) { for (int i = error.Location.Start.Line; i <= error.Location.End.Line; i++) { if (!neededLines.Contains(i)) { neededLines.Add(i); } } error = error.InnerError; } neededLines.Sort(); var lineDictionary = new TinyDictionary <int, string>(); var positionalTokenizer = new PositionalTokenizer(tokenizer); int lineIndex = 0; while (lineIndex < neededLines.Count) { while (positionalTokenizer.NextChar != '\0' && positionalTokenizer.Line != neededLines[lineIndex]) { positionalTokenizer.ReadTo('\n'); positionalTokenizer.Advance(); } lineDictionary[neededLines[lineIndex]] = positionalTokenizer.ReadTo('\n').TrimRight().ToString(); lineIndex++; } var builder = new StringBuilder(); error = Error; while (error != null) { builder.AppendFormat("{0}:{1} {2}", error.Location.Start.Line, error.Location.Start.Column, error.Message); builder.AppendLine(); //for (int i = error.Line; i <= error.EndLine; i++) int i = error.Location.Start.Line; // TODO: show all lines associated to error? { var line = lineDictionary[error.Location.Start.Line]; builder.Append(":: "); var startColumn = 0; while (Char.IsWhiteSpace(line[startColumn])) { startColumn++; } if (i == error.Location.Start.Line) { builder.Append("{{color|#C0C0C0|"); builder.Append(line.Substring(startColumn, error.Location.Start.Column - startColumn - 1)); builder.Append("}}"); startColumn = error.Location.Start.Column - 1; } if (i == error.Location.End.Line) { builder.Append(line.Substring(startColumn, error.Location.End.Column - startColumn)); builder.Append("{{color|#C0C0C0|"); builder.Append(line.Substring(error.Location.End.Column)); builder.Append("}}"); } else { builder.Append(line.Substring(startColumn)); } builder.AppendLine(); } builder.AppendLine(); error = error.InnerError; } while (builder.Length > 0 && Char.IsWhiteSpace(builder[builder.Length - 1])) { builder.Length--; } return(builder.ToString()); }
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 + ")"); } }); } }
public InterpreterScope() { _functions = new TinyDictionary <string, FunctionDefinitionExpression>(); _variables = new TinyDictionary <string, KeyValuePair <VariableDefinitionExpression, ExpressionBase> >(); }
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); } }