public static bool Read(Stream stream, out IODocument circuitDocument, out DocumentLoadResult loadResult) { try { BinaryReader reader = new BinaryReader(stream); int magicNumber = reader.ReadInt32(); int formatVersion = reader.ReadInt32(); string appVersion = reader.ReadString(); CDDXContentEncoding contentFlags = (CDDXContentEncoding)reader.ReadInt32(); uint contentOffset = 0; if (formatVersion >= 2) { contentOffset = reader.ReadUInt32(); // offset to content } if (formatVersion >= 2) { stream.Seek(contentOffset, SeekOrigin.Begin); } CircuitDocument newDocument = new CircuitDocument(); if ((contentFlags & CDDXContentEncoding.Deflate) == CDDXContentEncoding.Deflate) { DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress); Xml.XmlReader xmlReader = new Xml.XmlReader(); bool result = xmlReader.Load(deflateStream); circuitDocument = xmlReader.Document; loadResult = xmlReader.LoadResult; loadResult.Format = "CDDX (Legacy 1.0)"; return(result); } else { Xml.XmlReader xmlReader = new Xml.XmlReader(); bool result = xmlReader.Load(stream); circuitDocument = xmlReader.Document; loadResult = xmlReader.LoadResult; loadResult.Format = "CDDX (Legacy 1.0)"; return(result); } } catch (Exception) { circuitDocument = null; loadResult = new DocumentLoadResult(); loadResult.Type = DocumentLoadResultType.FailIncorrectFormat; return(false); } }
public static bool Read(Stream stream, out IODocument circuitDocument, out DocumentLoadResult loadResult) { try { BinaryReader reader = new BinaryReader(stream); int magicNumber = reader.ReadInt32(); int formatVersion = reader.ReadInt32(); string appVersion = reader.ReadString(); CDDXContentEncoding contentFlags = (CDDXContentEncoding)reader.ReadInt32(); uint contentOffset = 0; if (formatVersion >= 2) contentOffset = reader.ReadUInt32(); // offset to content if (formatVersion >= 2) stream.Seek(contentOffset, SeekOrigin.Begin); CircuitDocument newDocument = new CircuitDocument(); if ((contentFlags & CDDXContentEncoding.Deflate) == CDDXContentEncoding.Deflate) { DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress); Xml.XmlReader xmlReader = new Xml.XmlReader(); bool result = xmlReader.Load(deflateStream); circuitDocument = xmlReader.Document; loadResult = xmlReader.LoadResult; loadResult.Format = "CDDX (Legacy 1.0)"; return result; } else { Xml.XmlReader xmlReader = new Xml.XmlReader(); bool result = xmlReader.Load(stream); circuitDocument = xmlReader.Document; loadResult = xmlReader.LoadResult; loadResult.Format = "CDDX (Legacy 1.0)"; return result; } } catch (Exception) { circuitDocument = null; loadResult = new DocumentLoadResult(); loadResult.Type = DocumentLoadResultType.FailIncorrectFormat; return false; } }
public void TestGetComponentTypes() { // Create the component types var com1 = new IOComponentType("component1"); var com2 = new IOComponentType("collection1", "component2"); var com3 = new IOComponentType("collection1", "component3"); // Create the test document IODocument doc = new IODocument(); // Add instances of each component doc.Components.Add(new IOComponent("1", null, null, null, null, com1)); doc.Components.Add(new IOComponent("1", null, null, null, null, com2)); doc.Components.Add(new IOComponent("1", null, null, null, null, com3)); // Add a duplicate of component 3 doc.Components.Add(new IOComponent("1", null, null, null, null, com3)); // Call the method being tested var comTypes = doc.GetComponentTypes(); // There should be a "special:unknown" collection, // and a "collection1" collection Assert.AreEqual(2, comTypes.Count); Assert.IsTrue(comTypes.ContainsKey(IODocument.UnknownCollection)); Assert.IsTrue(comTypes.ContainsKey("collection1")); // "special:unknown" should contain "component1" Assert.AreEqual(1, comTypes[IODocument.UnknownCollection].Count); Assert.IsTrue(comTypes[IODocument.UnknownCollection].Contains(com1)); // "collection1" should contain "component2" and "component3" Assert.AreEqual(2, comTypes["collection1"].Count); Assert.IsTrue(comTypes["collection1"].Contains(com2)); Assert.IsTrue(comTypes["collection1"].Contains(com3)); }
/// <summary> /// Loads the main document part of a CDDX file. /// </summary> /// <param name="package">The package containing the document to load.</param> /// <returns>True if succeeded, false otherwise.</returns> bool LoadMainDocument(Package package) { // Open the document part PackageRelationship documentRelationship = package.GetRelationshipsByType(RelationshipTypes.Document).FirstOrDefault(); PackagePart documentPart = package.GetPart(documentRelationship.TargetUri); using (Stream docStream = documentPart.GetStream(FileMode.Open)) { Document = new IODocument(); XmlDocument doc = new XmlDocument(); doc.Load(docStream); // Set up namespaces XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.NameTable); namespaceManager.AddNamespace("cdd", Namespaces.Document); namespaceManager.AddNamespace("ec", Namespaces.DocumentComponentDescriptions); // Read version double version = 1.0; XmlElement rootElement = doc.SelectSingleNode("/cdd:circuit", namespaceManager) as XmlElement; if (rootElement != null && rootElement.HasAttribute("version")) { double.TryParse(rootElement.Attributes["version"].InnerText, out version); } if (version > FormatVersion) { m_newerVersion = true; } if (m_newerVersion) { LoadResult.Type = DocumentLoadResultType.SuccessNewerVersion; } else { LoadResult.Type = DocumentLoadResultType.Success; } // Read size double width = 640d; double height = 480d; XmlNode widthNode = doc.SelectSingleNode("/cdd:circuit/cdd:properties/cdd:width", namespaceManager); if (widthNode != null) { double.TryParse(widthNode.InnerText, out width); } XmlNode heightNode = doc.SelectSingleNode("/cdd:circuit/cdd:properties/cdd:height", namespaceManager); if (heightNode != null) { double.TryParse(heightNode.InnerText, out height); } Document.Size = new Size(width, height); // Read sources m_typeParts.Clear(); Dictionary <string, IOComponentType> componentTypes = new Dictionary <string, IOComponentType>(); // for use when loading component elements XmlNodeList componentSourceNodes = doc.SelectNodes("/cdd:circuit/cdd:definitions/cdd:src", namespaceManager); foreach (XmlElement source in componentSourceNodes) { // Read collection string collection = null; if (source.HasAttribute("col")) { collection = source.Attributes["col"].InnerText; } foreach (XmlElement addType in source.SelectNodes("cdd:add", namespaceManager)) { // Read item string typeId = addType.Attributes["id"].InnerText; string item = null; if (addType.HasAttribute("item")) { item = addType.Attributes["item"].InnerText; } // Read additional attributes for opening with the same component description string name = null; if (addType.HasAttribute("name", Namespaces.DocumentComponentDescriptions)) { name = addType.Attributes["name", Namespaces.DocumentComponentDescriptions].InnerText; } Guid guid = Guid.Empty; if (addType.HasAttribute("guid", Namespaces.DocumentComponentDescriptions)) { guid = new Guid(addType.Attributes["guid", Namespaces.DocumentComponentDescriptions].InnerText); } // Create new IOComponentType IOComponentType type = new IOComponentType(collection, item); type.Name = name; type.GUID = guid; // Read additional attributes for embedding if (addType.HasAttribute("id", Namespaces.Relationships)) { string relationshipId = addType.Attributes["id", Namespaces.Relationships].InnerText; PackageRelationship relationship = documentPart.GetRelationship(relationshipId); PackagePart embeddedTypePart = package.GetPart(PackUriHelper.ResolvePartUri(documentPart.Uri, relationship.TargetUri)); m_typeParts.Add(type, embeddedTypePart); } componentTypes.Add(typeId, type); } } // Read wire elements XmlNodeList wires = doc.SelectNodes("/cdd:circuit/cdd:elements//cdd:w", namespaceManager); foreach (XmlElement wire in wires) { // Read wire double x = double.Parse(wire.Attributes["x"].InnerText); double y = double.Parse(wire.Attributes["y"].InnerText); Orientation orientation = Orientation.Vertical; if (wire.HasAttribute("o") && wire.Attributes["o"].InnerText.ToLowerInvariant() == "h") { orientation = Orientation.Horizontal; } double size = 10d; if (wire.HasAttribute("sz")) { size = double.Parse(wire.Attributes["sz"].InnerText); } Document.Wires.Add(new IOWire(new Point(x, y), size, orientation)); } // Read component elements XmlNodeList componentElements = doc.SelectNodes("/cdd:circuit/cdd:elements//cdd:c", namespaceManager); foreach (XmlElement element in componentElements) { // Read component element string id = null; if (element.HasAttribute("id")) { id = element.Attributes["id"].InnerText; } string typeId = element.Attributes["tp"].InnerText; // Read layout information Point?location = null; if (element.HasAttribute("x") && element.HasAttribute("y")) { location = new Point(double.Parse(element.Attributes["x"].InnerText), double.Parse(element.Attributes["y"].InnerText)); } double?size = null; if (element.HasAttribute("sz")) { size = double.Parse(element.Attributes["sz"].InnerText); } Orientation?orientation = null; if (element.HasAttribute("o") && element.Attributes["o"].InnerText.ToLowerInvariant() == "h") { orientation = Orientation.Horizontal; } else if (element.HasAttribute("o") && element.Attributes["o"].InnerText.ToLowerInvariant() == "v") { orientation = Orientation.Vertical; } bool?flipped = null; if (element.HasAttribute("flp") && element.Attributes["flp"].InnerText.ToLowerInvariant() == "false") { flipped = false; } else if (element.HasAttribute("flp")) { flipped = true; } // Read properties List <IOComponentProperty> properties = new List <IOComponentProperty>(); XmlNodeList propertyNodes = element.SelectNodes("cdd:prs/cdd:p", namespaceManager); foreach (XmlElement property in propertyNodes) { // Read property string key = property.Attributes["k"].InnerText; string value = property.Attributes["v"].InnerText; bool isStandard = true; if (property.HasAttribute("st", Namespaces.DocumentComponentDescriptions) && property.Attributes["st", Namespaces.DocumentComponentDescriptions].InnerText == "false") { isStandard = false; } properties.Add(new IOComponentProperty(key, value, isStandard)); } // Read connections Dictionary <string, string> connections = new Dictionary <string, string>(); XmlNodeList connectionNodes = element.SelectNodes("cdd:cns/cdd:cn", namespaceManager); foreach (XmlNode connection in connectionNodes) { // Read connection string point = connection.Attributes["pt"].InnerText; string connectionId = connection.Attributes["id"].InnerText; connections.Add(point, connectionId); } // Find type IOComponentType type = null; if (typeId.StartsWith("{") && typeId.EndsWith("}")) { // Type in expected format: {0} string typeIdOnly = typeId.Substring(1, typeId.Length - 2); // Remove curly braces if (componentTypes.ContainsKey(typeIdOnly)) { type = componentTypes[typeIdOnly]; } else { throw new NotSupportedException(); // Undefined type } } Document.Components.Add(new IOComponent(id, location, size, flipped, orientation, type, properties, connections)); } return(true); } }
private bool LoadVersion1_1(XmlDocument doc) { try { Document = new IODocument(); XmlElement circuitNode = doc.SelectSingleNode("/circuit") as XmlElement; if (circuitNode.HasAttribute("width") && circuitNode.HasAttribute("height")) Document.Size = new System.Windows.Size(double.Parse(circuitNode.Attributes["width"].InnerText), double.Parse(circuitNode.Attributes["height"].InnerText)); string application = null; string appVersion = null; if (circuitNode.HasAttribute("application")) { application = circuitNode.Attributes["application"].InnerText; if (circuitNode.HasAttribute("appversion")) appVersion = circuitNode.Attributes["appversion"].InnerText; } else if (circuitNode.HasAttribute("cd-version")) { application = "Circuit Diagram "; appVersion = circuitNode.Attributes["cd-version"].InnerText; } XmlNodeList componentNodes = doc.SelectNodes("/circuit/component"); foreach (XmlNode node in componentNodes) { string type = node.Attributes["type"].InnerText; double x = double.Parse(node.Attributes["x"].InnerText); double y = double.Parse(node.Attributes["y"].InnerText); double size = 10d; if ((node as XmlElement).HasAttribute("size")) size = double.Parse(node.Attributes["size"].InnerText); bool horizontal = true; if ((node as XmlElement).HasAttribute("orientation") && node.Attributes["orientation"].InnerText.ToLowerInvariant() == "vertical") horizontal = false; Guid guid = Guid.Empty; if ((node as XmlElement).HasAttribute("guid")) guid = new Guid(node.Attributes["guid"].InnerText); // Check component type string lType = type.ToLowerInvariant(); if (lType == "wire") { // Element is wire IOWire wire = new IOWire(); wire.Location = new System.Windows.Point(x, y); wire.Orientation = (horizontal ? Orientation.Horizontal : Orientation.Vertical); wire.Size = size; // Add to document Document.Wires.Add(wire); } else { // Element is component IOComponent component = new IOComponent(); component.Location = new System.Windows.Point(x, y); component.Orientation = (horizontal ? Orientation.Horizontal : Orientation.Vertical); component.Size = size; // Other properties Dictionary<string, object> properties = new Dictionary<string, object>(node.Attributes.Count); foreach (XmlAttribute attribute in node.Attributes) properties.Add(attribute.Name, attribute.InnerText); // Read type parameter string t = null; if ((node as XmlElement).HasAttribute("t")) t = node.Attributes["t"].InnerText; if (t == null && lType == "logicgate" && (node as XmlElement).HasAttribute("logictype")) t = node.Attributes["logictype"].InnerText; if (properties.ContainsKey("flipped")) { component.IsFlipped = bool.Parse(properties["flipped"].ToString()); properties.Remove("flipped"); } // Convert component name string componentCollection; string standardComponentName; ConvertComponentName(lType, t, out componentCollection, out standardComponentName); // Set properties ConvertProperties(componentCollection, standardComponentName, properties); foreach (var property in properties) component.Properties.Add(new IOComponentProperty(property.Key, property.Value, true)); // Set type component.Type = new IOComponentType(componentCollection, standardComponentName); component.Type.Name = type; component.Type.GUID = guid; // Add to document Document.Components.Add(component); } } // Set metadata Document.Metadata.Application = application; Document.Metadata.AppVersion = appVersion; LoadResult = new DocumentLoadResult(); LoadResult.Format = "XML (1.1)"; LoadResult.Type = DocumentLoadResultType.Success; return true; } catch (Exception) { // Wrong format LoadResult = new DocumentLoadResult(); LoadResult.Type = DocumentLoadResultType.FailIncorrectFormat; return false; } }
private bool LoadVersion1_0(XmlDocument doc) { try { DocumentLoadResult loadResult = new DocumentLoadResult(); Document = new IODocument(); XmlElement circuitNode = doc.SelectSingleNode("/circuit") as XmlElement; if (circuitNode.HasAttribute("width") && circuitNode.HasAttribute("height")) Document.Size = new System.Windows.Size(double.Parse(circuitNode.Attributes["width"].InnerText), double.Parse(circuitNode.Attributes["height"].InnerText)); string application = null; string appVersion = null; if (circuitNode.HasAttribute("application")) application = circuitNode.Attributes["application"].InnerText; else if (circuitNode.HasAttribute("cd-version")) { application = "Circuit Diagram "; appVersion = circuitNode.Attributes["cd-version"].InnerText; } foreach (XmlNode node in circuitNode.ChildNodes) { if (node.NodeType != XmlNodeType.Element) continue; string type = node.Name; string location = node.Attributes["location"].InnerText; string[] locationSplit = location.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); // Snap points to grid double x = Math.Round(double.Parse(locationSplit[0]) / 10d) * 10d; double y = Math.Round(double.Parse(locationSplit[1]) / 10d) * 10d; double endX = Math.Round(double.Parse(locationSplit[2]) / 10d) * 10d; double endY = Math.Round(double.Parse(locationSplit[3]) / 10d) * 10d; double size = endX - x; bool horizontal = true; if (endX == x) { size = endY - y; horizontal = false; } // Other properties Dictionary<string, object> properties = new Dictionary<string, object>(node.Attributes.Count); foreach (XmlAttribute attribute in node.Attributes) properties.Add(attribute.Name, attribute.InnerText); string lType = type.ToLowerInvariant(); if (lType == "wire") { // Wire IOWire wire = new IOWire(); wire.Location = new System.Windows.Point(x, y); wire.Size = size; wire.Orientation = (horizontal ? Orientation.Horizontal : Orientation.Vertical); // Add to document Document.Wires.Add(wire); } else { // Full component IOComponent component = new IOComponent(); component.Location = new System.Windows.Point(x, y); component.Size = size; component.Orientation = (horizontal ? Orientation.Horizontal : Orientation.Vertical); // Read type parameter string t = null; if ((node as XmlElement).HasAttribute("t")) t = node.Attributes["t"].InnerText; else if ((node as XmlElement).HasAttribute("type")) t = node.Attributes["type"].InnerText; if (properties.ContainsKey("t")) properties.Remove("t"); // Convert component name string componentCollection; string standardComponentName; ConvertComponentName(lType, t, out componentCollection, out standardComponentName); // Set properties ConvertProperties(componentCollection, standardComponentName, properties); foreach (var property in properties) component.Properties.Add(new IOComponentProperty(property.Key, property.Value, true)); // Set type component.Type = new IOComponentType(componentCollection, standardComponentName); component.Type.Name = type; // Add to document Document.Components.Add(component); } } // Reset metadata Document.Metadata = new CircuitDocumentMetadata(); LoadResult.Format = "XML (1.0)"; Document.Metadata.Application = application; Document.Metadata.AppVersion = appVersion; LoadResult.Type = DocumentLoadResultType.Success; return true; } catch (Exception) { // Wrong format LoadResult = new DocumentLoadResult(); LoadResult.Type = DocumentLoadResultType.FailIncorrectFormat; return false; } }
private bool LoadVersion1_1(XmlDocument doc) { try { Document = new IODocument(); XmlElement circuitNode = doc.SelectSingleNode("/circuit") as XmlElement; if (circuitNode.HasAttribute("width") && circuitNode.HasAttribute("height")) { Document.Size = new Size(double.Parse(circuitNode.Attributes["width"].InnerText), double.Parse(circuitNode.Attributes["height"].InnerText)); } string application = null; string appVersion = null; if (circuitNode.HasAttribute("application")) { application = circuitNode.Attributes["application"].InnerText; if (circuitNode.HasAttribute("appversion")) { appVersion = circuitNode.Attributes["appversion"].InnerText; } } else if (circuitNode.HasAttribute("cd-version")) { application = "Circuit Diagram "; appVersion = circuitNode.Attributes["cd-version"].InnerText; } XmlNodeList componentNodes = doc.SelectNodes("/circuit/component"); foreach (XmlNode node in componentNodes) { string type = node.Attributes["type"].InnerText; double x = double.Parse(node.Attributes["x"].InnerText); double y = double.Parse(node.Attributes["y"].InnerText); double size = 10d; if ((node as XmlElement).HasAttribute("size")) { size = double.Parse(node.Attributes["size"].InnerText); } bool horizontal = true; if ((node as XmlElement).HasAttribute("orientation") && node.Attributes["orientation"].InnerText.ToLowerInvariant() == "vertical") { horizontal = false; } Guid guid = Guid.Empty; if ((node as XmlElement).HasAttribute("guid")) { guid = new Guid(node.Attributes["guid"].InnerText); } // Check component type string lType = type.ToLowerInvariant(); if (lType == "wire") { // Element is wire IOWire wire = new IOWire(); wire.Location = new Point(x, y); wire.Orientation = (horizontal ? Orientation.Horizontal : Orientation.Vertical); wire.Size = size; // Add to document Document.Wires.Add(wire); } else { // Element is component IOComponent component = new IOComponent(); component.Location = new Point(x, y); component.Orientation = (horizontal ? Orientation.Horizontal : Orientation.Vertical); component.Size = size; // Other properties Dictionary <string, object> properties = new Dictionary <string, object>(node.Attributes.Count); foreach (XmlAttribute attribute in node.Attributes) { properties.Add(attribute.Name, attribute.InnerText); } // Read type parameter string t = null; if ((node as XmlElement).HasAttribute("t")) { t = node.Attributes["t"].InnerText; } if (t == null && lType == "logicgate" && (node as XmlElement).HasAttribute("logictype")) { t = node.Attributes["logictype"].InnerText; } if (properties.ContainsKey("flipped")) { component.IsFlipped = bool.Parse(properties["flipped"].ToString()); properties.Remove("flipped"); } // Convert component name string componentCollection; string standardComponentName; ConvertComponentName(lType, t, out componentCollection, out standardComponentName); // Set properties ConvertProperties(componentCollection, standardComponentName, properties); foreach (var property in properties) { component.Properties.Add(new IOComponentProperty(property.Key, property.Value, true)); } // Set type component.Type = new IOComponentType(componentCollection, standardComponentName); component.Type.Name = type; component.Type.GUID = guid; // Add to document Document.Components.Add(component); } } // Set metadata Document.Metadata.Application = application; Document.Metadata.AppVersion = appVersion; LoadResult = new DocumentLoadResult(); LoadResult.Format = "XML (1.1)"; LoadResult.Type = DocumentLoadResultType.Success; return(true); } catch (Exception) { // Wrong format LoadResult = new DocumentLoadResult(); LoadResult.Type = DocumentLoadResultType.FailIncorrectFormat; return(false); } }
private bool LoadVersion1_0(XmlDocument doc) { try { DocumentLoadResult loadResult = new DocumentLoadResult(); Document = new IODocument(); XmlElement circuitNode = doc.SelectSingleNode("/circuit") as XmlElement; if (circuitNode.HasAttribute("width") && circuitNode.HasAttribute("height")) { Document.Size = new Size(double.Parse(circuitNode.Attributes["width"].InnerText), double.Parse(circuitNode.Attributes["height"].InnerText)); } string application = null; string appVersion = null; if (circuitNode.HasAttribute("application")) { application = circuitNode.Attributes["application"].InnerText; } else if (circuitNode.HasAttribute("cd-version")) { application = "Circuit Diagram "; appVersion = circuitNode.Attributes["cd-version"].InnerText; } foreach (XmlNode node in circuitNode.ChildNodes) { if (node.NodeType != XmlNodeType.Element) { continue; } string type = node.Name; string location = node.Attributes["location"].InnerText; string[] locationSplit = location.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); // Snap points to grid double x = Math.Round(double.Parse(locationSplit[0]) / 10d) * 10d; double y = Math.Round(double.Parse(locationSplit[1]) / 10d) * 10d; double endX = Math.Round(double.Parse(locationSplit[2]) / 10d) * 10d; double endY = Math.Round(double.Parse(locationSplit[3]) / 10d) * 10d; double size = endX - x; bool horizontal = true; if (endX == x) { size = endY - y; horizontal = false; } // Other properties Dictionary <string, object> properties = new Dictionary <string, object>(node.Attributes.Count); foreach (XmlAttribute attribute in node.Attributes) { properties.Add(attribute.Name, attribute.InnerText); } string lType = type.ToLowerInvariant(); if (lType == "wire") { // Wire IOWire wire = new IOWire(); wire.Location = new Point(x, y); wire.Size = size; wire.Orientation = (horizontal ? Orientation.Horizontal : Orientation.Vertical); // Add to document Document.Wires.Add(wire); } else { // Full component var component = new IOComponent(); component.Location = new Point(x, y); component.Size = size; component.Orientation = (horizontal ? Orientation.Horizontal : Orientation.Vertical); // Read type parameter string t = null; if ((node as XmlElement).HasAttribute("t")) { t = node.Attributes["t"].InnerText; } else if ((node as XmlElement).HasAttribute("type")) { t = node.Attributes["type"].InnerText; } if (properties.ContainsKey("t")) { properties.Remove("t"); } // Convert component name string componentCollection; string standardComponentName; ConvertComponentName(lType, t, out componentCollection, out standardComponentName); // Set properties ConvertProperties(componentCollection, standardComponentName, properties); foreach (var property in properties) { component.Properties.Add(new IOComponentProperty(property.Key, property.Value, true)); } // Set type component.Type = new IOComponentType(componentCollection, standardComponentName); component.Type.Name = type; // Add to document Document.Components.Add(component); } } // Reset metadata Document.Metadata = new CircuitDocumentMetadata(); LoadResult.Format = "XML (1.0)"; Document.Metadata.Application = application; Document.Metadata.AppVersion = appVersion; LoadResult.Type = DocumentLoadResultType.Success; return(true); } catch (Exception) { // Wrong format LoadResult = new DocumentLoadResult(); LoadResult.Type = DocumentLoadResultType.FailIncorrectFormat; return(false); } }
/// <summary> /// Converts a <see cref="CircuitDocument"/> to an <see cref="IODocument"/>. /// </summary> /// <param name="document">The CircuitDocument to convert.</param> /// <returns>An IODocument constructed from the CircuitDocument.</returns> public static IODocument ToIODocument(this CircuitDocument document, out IDictionary <IOComponentType, EmbedComponentData> embedComponents) { IODocument ioDocument = new IODocument(); ioDocument.Size = document.Size; // Set metadata ioDocument.Metadata = document.Metadata; // Get connections Dictionary <Component, Dictionary <string, string> > connections = ConnectionHelper.RemoveWires(document); // Generate types Dictionary <ComponentIdentifier, IOComponentType> componentTypes = new Dictionary <ComponentIdentifier, IOComponentType>(); foreach (Component component in document.Components) { if (ComponentHelper.IsWire(component)) { continue; // Skip wires } ComponentIdentifier identifier = new ComponentIdentifier(component.Description, component.Configuration()); if (!componentTypes.ContainsKey(identifier)) { IOComponentType ioType = new IOComponentType(component.Description.Metadata.ImplementSet, (identifier.Configuration != null && !String.IsNullOrEmpty(identifier.Configuration.ImplementationName) ? identifier.Configuration.ImplementationName : component.Description.Metadata.ImplementItem)); ioType.Name = component.Description.ComponentName; ioType.GUID = component.Description.Metadata.GUID; componentTypes.Add(identifier, ioType); } } // Add visible components int idCounter = 0; // generate component IDs foreach (IComponentElement component in document.Elements.Where(component => component is IComponentElement && !ComponentHelper.IsWire(component))) { IOComponent ioComponent = new IOComponent(); ioComponent.ID = idCounter.ToString(); ioComponent.Size = component.Size; ioComponent.Location = new Point(component.Location.X, component.Location.Y); ioComponent.IsFlipped = component.IsFlipped; ioComponent.Orientation = component.Orientation; IOComponentType ioType = new IOComponentType(component.ImplementationCollection, component.ImplementationItem); if (component is Component) { Component cComponent = component as Component; ioType.Name = cComponent.Description.ComponentName; ioType.GUID = cComponent.Description.Metadata.GUID; ioComponent.Type = ioType; // Set connections if (connections.ContainsKey(cComponent)) { foreach (var connection in connections[cComponent]) { ioComponent.Connections.Add(connection.Key, connection.Value); } } } // Set properties foreach (var property in component.Properties) { ioComponent.Properties.Add(new IOComponentProperty(property.Key, property.Value, true)); // TODO: implement IsStandard } ioDocument.Components.Add(ioComponent); idCounter++; } // Add unavailable components foreach (DisabledComponent component in document.DisabledComponents) { Point?location = null; if (component.Location.HasValue) { location = new Point(component.Location.Value.X, component.Location.Value.Y); } IOComponent ioComponent = new IOComponent(); ioComponent.ID = idCounter.ToString(); ioComponent.Location = location; ioComponent.Size = component.Size; ioComponent.IsFlipped = component.IsFlipped; ioComponent.Orientation = component.Orientation; IOComponentType ioType = new IOComponentType(component.ImplementationCollection, component.ImplementationItem); // Set name if (!String.IsNullOrEmpty(component.Name)) { ioType.Name = component.Name; } // Set GUID if (component.GUID.HasValue) { ioType.GUID = component.GUID.Value; } ioComponent.Type = ioType; // Set properties foreach (var property in component.Properties) { ioComponent.Properties.Add(new IOComponentProperty(property.Key, property.Value, true)); } ioDocument.Components.Add(ioComponent); idCounter++; } // Add wires foreach (IComponentElement wire in document.Components.Where(component => ComponentHelper.IsWire(component))) { IOWire ioWire = new IOWire(new Point(wire.Location.X, wire.Location.Y), wire.Size, wire.Orientation); ioDocument.Wires.Add(ioWire); } // Embed components embedComponents = new Dictionary <IOComponentType, EmbedComponentData>(); foreach (EmbedDescription embedItem in document.Metadata.EmbedComponents.Where(item => item.IsEmbedded == true)) { if (!String.IsNullOrEmpty(embedItem.Description.Source.Path) && System.IO.File.Exists(embedItem.Description.Source.Path)) { EmbedComponentData embedData = new EmbedComponentData(); embedData.Stream = System.IO.File.OpenRead(embedItem.Description.Source.Path); embedData.FileExtension = System.IO.Path.GetExtension(embedItem.Description.Source.Path); switch (embedData.FileExtension) { case ".xml": embedData.ContentType = "application/xml"; break; case ".cdcom": embedData.ContentType = IO.CDDX.ContentTypeNames.BinaryComponent; break; } List <IOComponentType> associatedTypes = new List <IOComponentType>(); foreach (var item in componentTypes) { if (item.Key.Description == embedItem.Description && !embedComponents.ContainsKey(item.Value)) { embedComponents.Add(item.Value, embedData); } } } } return(ioDocument); }
/// <summary> /// Converts a <see cref="IODocument"/> to a <see cref="CircuitDocument"/>. /// </summary> /// <param name="document">The IODocument to convert.</param> /// <returns>A CircuitDocument constructed from the IODocument.</returns> public static CircuitDocument ToCircuitDocument(this IODocument document, IDocumentReader reader, out List <IOComponentType> unavailableComponents) { CircuitDocument circuitDocument = new CircuitDocument(); circuitDocument.Size = document.Size; // Set metadata circuitDocument.Metadata = new CircuitDocumentMetadata(null, null, document.Metadata); // Add components unavailableComponents = new List <IOComponentType>(); foreach (IOComponent component in document.Components) { ComponentIdentifier identifier = null; // Find description if (component.Type.GUID != Guid.Empty && ComponentHelper.IsDescriptionAvailable(component.Type.GUID)) { identifier = new ComponentIdentifier(ComponentHelper.FindDescription(component.Type.GUID)); } if (identifier == null && reader.IsDescriptionEmbedded(component.Type)) { identifier = LoadDescription(reader.GetEmbeddedDescription(component.Type), component.Type); } if (identifier == null && component.Type.IsStandard) { identifier = ComponentHelper.GetStandardComponent(component.Type.Collection, component.Type.Item); } if (identifier != null) { // Add full component Dictionary <string, object> properties = new Dictionary <string, object>(); foreach (var property in component.Properties) { properties.Add(property.Key, property.Value); } Component addComponent = Component.Create(identifier, properties); addComponent.Layout(component.Location.Value.X, component.Location.Value.Y, (component.Size.HasValue ? component.Size.Value : identifier.Description.MinSize), component.Orientation.Value, component.IsFlipped == true); addComponent.ImplementMinimumSize(addComponent.Description.MinSize); FlagOptions flagOptions = ComponentHelper.ApplyFlags(addComponent); if ((flagOptions & FlagOptions.HorizontalOnly) == FlagOptions.HorizontalOnly && component.Orientation == Orientation.Vertical) { addComponent.Orientation = Orientation.Horizontal; } else if ((flagOptions & FlagOptions.VerticalOnly) == FlagOptions.VerticalOnly && component.Orientation == Orientation.Horizontal) { addComponent.Orientation = Orientation.Vertical; } circuitDocument.Elements.Add(addComponent); } else { // Add disabled component if (!unavailableComponents.Contains(component.Type)) { unavailableComponents.Add(component.Type); } DisabledComponent addComponent = new DisabledComponent(); Dictionary <string, object> properties = new Dictionary <string, object>(); foreach (var property in component.Properties) { addComponent.Properties.Add(property.Key, property.Value); } addComponent.ImplementationCollection = component.Type.Collection; addComponent.ImplementationItem = component.Type.Item; addComponent.Name = component.Type.Name; addComponent.GUID = component.Type.GUID; if (component.Location.HasValue) { addComponent.Location = new Vector(component.Location.Value.X, component.Location.Value.Y); } addComponent.Size = component.Size; addComponent.Orientation = component.Orientation; circuitDocument.DisabledComponents.Add(addComponent); } } // Add wires IOComponentType wireType = new IOComponentType("wire"); if (ComponentHelper.WireDescription == null) { unavailableComponents.Add(wireType); } else { foreach (IOWire wire in document.Wires) { Dictionary <string, object> properties = new Dictionary <string, object>(4); properties.Add("@x", wire.Location.X); properties.Add("@y", wire.Location.Y); properties.Add("@orientation", wire.Orientation == Orientation.Horizontal); properties.Add("@size", wire.Size); Component wireComponent = Component.Create(ComponentHelper.WireDescription, properties); wireComponent.Layout(wire.Location.X, wire.Location.Y, wire.Size, wire.Orientation, false); wireComponent.ApplyConnections(circuitDocument); circuitDocument.Elements.Add(wireComponent); } } // Connections foreach (Component component in circuitDocument.Components) { component.ApplyConnections(circuitDocument); } return(circuitDocument); }