Exemplo n.º 1
0
 /// <returns>True when flag was unsed when parsing</returns>
 /// <returns>Flase when flag was not unsed when parsing</returns>
 /// <param name="flag"></param>
 public bool GetFlagValue(string flag)
 {
     if (!IsSuccess)
     {
         throw new InvalidOperationException("only can get flag value when parse succeed");
     }
     if (string.IsNullOrEmpty(flag))
     {
         throw new ArgumentNullException(nameof(flag));
     }
     if (flag.StartsWith("--"))
     {
         var option = flag.Substring(2, flag.Length - 2);
         if (!FlagRegex.FullFormRegex.IsMatch(option))
         {
             throw new ArgumentException("flag is invalid");
         }
         return(FlagOptions.Any(f => string.Equals(f.SymbolMetadata.FullForm, option, StringComparison.OrdinalIgnoreCase)));
     }
     if (flag.StartsWith("-"))
     {
         var option = flag.Substring(1, flag.Length - 1);
         if (!FlagRegex.AbbrevationFormRegex.IsMatch(option))
         {
             throw new ArgumentException("flag is invalid");
         }
         return(FlagOptions.Any(f => string.Equals(f.SymbolMetadata.Abbreviation.ToString(), option, StringComparison.OrdinalIgnoreCase)));
     }
     return(false);
 }
Exemplo n.º 2
0
        private Conditional <FlagOptions> ReadFlagOptionNode(XElement flagElement, LoadContext lc)
        {
            IConditionTreeItem conditions = ConditionTree.Empty;
            var conditionsAttribute       = flagElement.Attribute("conditions");

            if (conditionsAttribute != null)
            {
                IXmlLineInfo line = conditionsAttribute as IXmlLineInfo;

                try
                {
                    conditions = lc.ConditionParser.Parse(conditionsAttribute.Value, lc.ParseContext);
                }
                catch (ConditionFormatException ex)
                {
                    lc.Errors.Add(new LoadError(lc.FileName, line.LineNumber, line.LinePosition + conditionsAttribute.Name.LocalName.Length + 2 + ex.PositionStart, LoadErrorCategory.Error, ex.Message));
                    return(null);
                }
            }

            FlagOptions theOptions = FlagOptions.None;

            foreach (var node in flagElement.Descendants(lc.NS + "option"))
            {
                theOptions |= (FlagOptions)Enum.Parse(typeof(FlagOptions), node.Value, true);
            }

            return(new Conditional <FlagOptions>(theOptions, conditions));
        }
Exemplo n.º 3
0
        public bool GetDefaultFlag(FlagOptions option)
        {
            var defaultFlags = Flags.FirstOrDefault(x => x.Conditions.Equals(ConditionTree.Empty));

            if (defaultFlags == null)
            {
                return(false);
            }
            return((defaultFlags.Value & option) == option);
        }
        public bool GetDefaultFlag(FlagOptions option)
        {
            foreach (var flagSet in Flags)
            {
                if (flagSet.Conditions.Equals(ConditionTree.Empty) && (flagSet.Value & option) == option)
                {
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 5
0
        public Point Resolve(Component component)
        {
            ComponentPoint tempPoint = this;

            if (component.IsFlipped == true)
            {
                tempPoint = Flip(component.Orientation == Orientation.Horizontal);
            }

            double x = tempPoint.Offset.X;
            double y = tempPoint.Offset.Y;

            if (tempPoint.RelativeToX == ComponentPosition.Middle && component.Orientation == Orientation.Horizontal)
            {
                x += component.Size / 2;
            }
            else if (tempPoint.RelativeToY == ComponentPosition.Middle && component.Orientation == Orientation.Vertical)
            {
                y += component.Size / 2;
            }

            if (tempPoint.RelativeToX == ComponentPosition.End && component.Orientation == Orientation.Horizontal)
            {
                x += component.Size;
            }
            else if (tempPoint.RelativeToY == ComponentPosition.End && component.Orientation == Orientation.Vertical)
            {
                y += component.Size;
            }

            FlagOptions flags = ComponentHelper.ApplyFlags(component);

            if ((flags & FlagOptions.MiddleMustAlign) == FlagOptions.MiddleMustAlign)
            {
                if (component.Orientation == Orientation.Horizontal && tempPoint.RelativeToX == ComponentPosition.Middle)
                {
                    if ((x - tempPoint.Offset.X) % ComponentHelper.GridSize != 0d)
                    {
                        x += 5d;
                    }
                }
                else if (tempPoint.RelativeToY == ComponentPosition.Middle)
                {
                    if ((y - tempPoint.Offset.Y) % ComponentHelper.GridSize != 0d)
                    {
                        y += 5d;
                    }
                }
            }

            return(new Point(x, y));
        }
        public FlagOptions DetermineFlags(PositionalComponent component)
        {
            FlagOptions returnOptions = FlagOptions.None;

            foreach (Conditional <FlagOptions> option in Flags)
            {
                if (option.Conditions.IsMet(component, this))
                {
                    returnOptions |= option.Value;
                }
            }

            return(returnOptions);
        }
Exemplo n.º 7
0
        public static FlagOptions ApplyFlags(Component component)
        {
            FlagOptions returnOptions = FlagOptions.None;

            foreach (Conditional <FlagOptions> option in component.Description.Flags)
            {
                if (option.Conditions.IsMet(component))
                {
                    returnOptions |= option.Value;
                }
            }

            return(returnOptions);
        }
        public void SetDefaultFlag(FlagOptions option, bool enabled)
        {
            var defaultFlags = Flags.FirstOrDefault(x => x.Conditions.Equals(ConditionTree.Empty));

            if (defaultFlags == null)
            {
                defaultFlags = new Conditional <FlagOptions>();
                Flags.Insert(0, defaultFlags);
            }

            if (enabled)
            {
                defaultFlags.Value = defaultFlags.Value | option;
            }
            else
            {
                defaultFlags.Value = defaultFlags.Value & ~option;
            }
        }
        private Conditional <FlagOptions> ReadFlagOptionNode(ComponentDescription description, XElement flagElement)
        {
            IConditionTreeItem conditions = ConditionTree.Empty;
            var conditionsAttribute       = flagElement.Attribute("conditions");

            if (conditionsAttribute != null)
            {
                conditionParser.Parse(conditionsAttribute, description, logger, out conditions);
            }

            FlagOptions theOptions = FlagOptions.None;

            foreach (var node in flagElement.Elements(flagElement.GetDefaultNamespace() + "option"))
            {
                theOptions |= (FlagOptions)Enum.Parse(typeof(FlagOptions), node.Value, true);
            }

            return(new Conditional <FlagOptions>(theOptions, conditions));
        }
Exemplo n.º 10
0
        internal override void Read(System.IO.BinaryReader reader, BinaryReadInfo readInfo)
        {
            uint length = reader.ReadUInt32();

            ID = reader.ReadUInt32();
            uint numSections = reader.ReadUInt32();

            string componentName = null;
            bool   canResize     = false;
            bool   canFlip       = false;
            double minSize       = ComponentHelper.GridSize;
            List <ComponentProperty>          properties          = new List <ComponentProperty>();
            List <ConnectionGroup>            connections         = new List <ConnectionGroup>();
            List <RenderDescription>          renderDescriptions  = new List <RenderDescription>();
            List <Conditional <FlagOptions> > flagOptions         = new List <Conditional <FlagOptions> >();
            ComponentDescriptionMetadata      descriptionMetadata = new ComponentDescriptionMetadata();
            uint?iconResourceId = null;

            for (uint sectionCounter = 0; sectionCounter < numSections; sectionCounter++)
            {
                ushort sectionType   = reader.ReadUInt16();
                uint   sectionLength = reader.ReadUInt32();

                #region Metadata
                if (sectionType == (uint)BinaryConstants.ComponentSectionType.Metadata)
                {
                    componentName              = reader.ReadString();
                    canResize                  = reader.ReadBoolean();
                    canFlip                    = reader.ReadBoolean();
                    minSize                    = reader.ReadDouble();
                    descriptionMetadata.Type   = String.Format("Binary r{0} (*.cdcom)", readInfo.FormatVersion);
                    descriptionMetadata.GUID   = new Guid(reader.ReadBytes(16));
                    descriptionMetadata.Author = reader.ReadString();
                    if (readInfo.IsSignatureValid && readInfo.Certificate != null && readInfo.IsCertificateTrusted)
                    {
                        descriptionMetadata.Author = readInfo.Certificate.GetNameInfo(X509NameType.EmailName, false);
                    }
                    descriptionMetadata.Version = new Version(reader.ReadUInt16(), reader.ReadUInt16());
                    descriptionMetadata.AdditionalInformation          = reader.ReadString();
                    descriptionMetadata.ImplementSet                   = reader.ReadString();
                    descriptionMetadata.ImplementItem                  = reader.ReadString();
                    descriptionMetadata.Signature.IsHashValid          = readInfo.IsSignatureValid;
                    descriptionMetadata.Signature.Certificate          = readInfo.Certificate;
                    descriptionMetadata.Signature.IsCertificateTrusted = readInfo.IsCertificateTrusted;
                    int iconResource = reader.ReadInt32();
                    if (iconResource != -1)
                    {
                        iconResourceId = (uint)iconResource;
                    }
                    long created = reader.ReadInt64();
                }
                #endregion
                #region Flags
                else if (sectionType == (uint)BinaryConstants.ComponentSectionType.Flags)
                {
                    uint numFlagGroups = reader.ReadUInt32();
                    for (uint j = 0; j < numFlagGroups; j++)
                    {
                        IConditionTreeItem conditions;
                        if (readInfo.FormatVersion > 1)
                        {
                            conditions = reader.ReadConditionTree();
                        }
                        else
                        {
                            conditions = reader.ReadConditionCollection();
                        }

                        FlagOptions value = (FlagOptions)reader.ReadUInt32();
                        flagOptions.Add(new Conditional <FlagOptions>(value, conditions));
                    }
                }
                #endregion
                #region Properties
                else if (sectionType == (uint)BinaryConstants.ComponentSectionType.Properties)
                {
                    uint numProperties = reader.ReadUInt32();
                    for (uint j = 0; j < numProperties; j++)
                    {
                        string        propertyName   = reader.ReadString();
                        string        serializedName = reader.ReadString();
                        string        displayName    = reader.ReadString();
                        BinaryType    propType;
                        object        rawDefaultValue = reader.ReadType(out propType);
                        PropertyUnion defaultValue    = propType.ToPropertyUnion(rawDefaultValue);
                        string[]      enumOptions     = null;
                        if (propType == BinaryType.Enum)
                        {
                            enumOptions = new string[reader.ReadInt32()];
                            for (int k = 0; k < enumOptions.Length; k++)
                            {
                                enumOptions[k] = reader.ReadString();
                            }
                        }

                        // Format rules
                        List <ComponentPropertyFormat> formatRules = new List <ComponentPropertyFormat>();
                        uint numFormatRules = reader.ReadUInt32();
                        for (uint k = 0; k < numFormatRules; k++)
                        {
                            IConditionTreeItem conditions;
                            if (readInfo.FormatVersion > 1)
                            {
                                conditions = reader.ReadConditionTree();
                            }
                            else
                            {
                                conditions = reader.ReadConditionCollection();
                            }
                            string formatRule = reader.ReadString();
                            formatRules.Add(new ComponentPropertyFormat(formatRule, conditions));
                        }

                        // Other conditions
                        uint numOtherConditions = reader.ReadUInt32();
                        Dictionary <PropertyOtherConditionType, IConditionTreeItem> otherConditions = new Dictionary <PropertyOtherConditionType, IConditionTreeItem>((int)numOtherConditions);
                        for (uint k = 0; k < numOtherConditions; k++)
                        {
                            uint uintConditionType = reader.ReadUInt32();
                            IConditionTreeItem conditions;
                            if (readInfo.FormatVersion > 1)
                            {
                                conditions = reader.ReadConditionTree();
                            }
                            else
                            {
                                conditions = reader.ReadConditionCollection();
                            }
                            PropertyOtherConditionType conditionType = (PropertyOtherConditionType)uintConditionType;
                            otherConditions.Add(conditionType, conditions);
                        }

                        properties.Add(new ComponentProperty(propertyName, serializedName, displayName, BinaryIOExtentions.BinaryTypeToPropertyType(propType), defaultValue, formatRules.ToArray(), otherConditions, enumOptions));
                    }
                }
                #endregion
                #region Configurations
                else if (sectionType == (uint)BinaryConstants.ComponentSectionType.Configurations)
                {
                    uint numConfigurations = reader.ReadUInt32();
                    for (int j = 0; j < numConfigurations; j++)
                    {
                        string configurationName  = reader.ReadString();
                        string implementationName = reader.ReadString();

                        int numSetters = reader.ReadInt32();
                        var setters    = new Dictionary <string, PropertyUnion>(numSetters);
                        for (int k = 0; k < numSetters; k++)
                        {
                            BinaryType tempType;
                            string     name        = reader.ReadString();
                            var        setterValue = reader.ReadType(out tempType);
                            setters.Add(name, tempType.ToPropertyUnion(setterValue));
                        }

                        int iconID = reader.ReadInt32();

                        var configuration = new ComponentConfiguration(implementationName, configurationName, setters);
                        descriptionMetadata.Configurations.Add(configuration);

                        if (iconID != -1)
                        {
                            iconResources.Add(configuration, (uint)iconID);
                        }
                    }
                }
                #endregion
                #region Connections
                else if (sectionType == (uint)BinaryConstants.ComponentSectionType.Connections)
                {
                    uint numConnectionGroups = reader.ReadUInt32();
                    List <ConnectionGroup> connectionGroups = new List <ConnectionGroup>();
                    for (int j = 0; j < numConnectionGroups; j++)
                    {
                        IConditionTreeItem conditions;
                        if (readInfo.FormatVersion > 1)
                        {
                            conditions = reader.ReadConditionTree();
                        }
                        else
                        {
                            conditions = reader.ReadConditionCollection();
                        }

                        List <ConnectionDescription> tConnections = new List <ConnectionDescription>();
                        uint numConnections = reader.ReadUInt32();
                        for (uint k = 0; k < numConnections; k++)
                        {
                            tConnections.Add(new ConnectionDescription(reader.ReadComponentPoint(), reader.ReadComponentPoint(), (ConnectionEdge)reader.ReadInt32(), reader.ReadString()));
                        }

                        connections.Add(new ConnectionGroup(conditions, tConnections.ToArray()));
                    }
                }
                #endregion
                #region Render
                else if (sectionType == (uint)BinaryConstants.ComponentSectionType.Render)
                {
                    uint numRenderGroups = reader.ReadUInt32();
                    for (uint j = 0; j < numRenderGroups; j++)
                    {
                        IConditionTreeItem conditions;
                        if (readInfo.FormatVersion > 1)
                        {
                            conditions = reader.ReadConditionTree();
                        }
                        else
                        {
                            conditions = reader.ReadConditionCollection();
                        }

                        int numRenderCommands = (int)reader.ReadUInt32();
                        List <IRenderCommand> renderCommands = new List <IRenderCommand>(numRenderCommands);
                        for (int k = 0; k < numRenderCommands; k++)
                        {
                            RenderCommandType commandType = (RenderCommandType)reader.ReadUInt32();
                            switch (commandType)
                            {
                            case RenderCommandType.Line:
                            {
                                ComponentPoint start     = reader.ReadComponentPoint();
                                ComponentPoint end       = reader.ReadComponentPoint();
                                double         thickness = reader.ReadDouble();
                                renderCommands.Add(new Line(start, end, thickness));
                            }
                                continue;

                            case RenderCommandType.Rect:
                            {
                                ComponentPoint location  = reader.ReadComponentPoint();
                                double         width     = reader.ReadDouble();
                                double         height    = reader.ReadDouble();
                                double         thickness = reader.ReadDouble();
                                bool           fill      = (reader.ReadUInt32() == 0 ? false : true);
                                renderCommands.Add(new Rectangle(location, width, height, thickness, fill));
                            }
                                continue;

                            case RenderCommandType.Ellipse:
                            {
                                ComponentPoint centre    = reader.ReadComponentPoint();
                                double         radiusX   = reader.ReadDouble();
                                double         radiusY   = reader.ReadDouble();
                                double         thickness = reader.ReadDouble();
                                bool           fill      = (reader.ReadUInt32() == 0 ? false : true);
                                renderCommands.Add(new Ellipse(centre, radiusX, radiusY, thickness, fill));
                            }
                                continue;

                            case RenderCommandType.Path:
                            {
                                ComponentPoint start     = reader.ReadComponentPoint();
                                double         thickness = reader.ReadDouble();
                                bool           fill      = (reader.ReadUInt32() == 0 ? false : true);

                                int numCommands = reader.ReadInt32();
                                List <IPathCommand> pathCommands = new List <IPathCommand>(numCommands);
                                for (int l = 0; l < numCommands; l++)
                                {
                                    CommandType  pType      = (CommandType)reader.ReadInt32();
                                    IPathCommand theCommand = null;
                                    switch (pType)
                                    {
                                    case CommandType.MoveTo:
                                        theCommand = new MoveTo();
                                        break;

                                    case CommandType.LineTo:
                                        theCommand = new LineTo();
                                        break;

                                    case CommandType.CurveTo:
                                        theCommand = new CurveTo();
                                        break;

                                    case CommandType.EllipticalArcTo:
                                        theCommand = new EllipticalArcTo();
                                        break;

                                    case CommandType.QuadraticBeizerCurveTo:
                                        theCommand = new QuadraticBeizerCurveTo();
                                        break;

                                    case CommandType.SmoothCurveTo:
                                        theCommand = new SmoothCurveTo();
                                        break;

                                    case CommandType.SmoothQuadraticBeizerCurveTo:
                                        theCommand = new SmoothQuadraticBeizerCurveTo();
                                        break;

                                    default:
                                        theCommand = new ClosePath();
                                        break;
                                    }
                                    theCommand.Read(reader);
                                    pathCommands.Add(theCommand);
                                }

                                renderCommands.Add(new RenderPath(start, thickness, fill, pathCommands));
                            }
                                continue;

                            case RenderCommandType.Text:
                            {
                                byte           formattedTextVersion = reader.ReadByte();
                                ComponentPoint location             = reader.ReadComponentPoint();
                                TextAlignment  alignment            = (TextAlignment)reader.ReadUInt32();

                                uint           numTextRuns = reader.ReadUInt32();
                                List <TextRun> textRuns    = new List <TextRun>((int)numTextRuns);
                                for (uint l = 0; l < numTextRuns; l++)
                                {
                                    TextRunFormattingType formattingType = (TextRunFormattingType)reader.ReadUInt32();
                                    double runSize = reader.ReadDouble();
                                    string runText = reader.ReadString();
                                    textRuns.Add(new TextRun(runText, new TextRunFormatting(formattingType, runSize)));
                                }

                                renderCommands.Add(new Text(location, alignment, textRuns));
                            }
                                continue;
                            }
                        }

                        renderDescriptions.Add(new RenderDescription(conditions, renderCommands.ToArray()));
                    }
                }
                #endregion
                #region Skip
                else
                {
                    // Unknown type - skip
                    reader.BaseStream.Seek(sectionLength, SeekOrigin.Current);
                }
                #endregion
            }

            ComponentDescription = new ComponentDescription(ID.ToString(), componentName, canResize, canFlip, minSize, properties.ToArray(), connections.ToArray(), renderDescriptions.ToArray(), flagOptions.ToArray(), descriptionMetadata);

            if (iconResourceId.HasValue)
            {
                mainIconResource = iconResourceId.Value;
            }
        }
Exemplo n.º 11
0
        public static T RenderPreview <T>(Func <Size, T> drawingContext,
                                          ComponentDescription desc,
                                          PreviewGenerationOptions options)
            where T : IDrawingContext
        {
            var componentType = new ComponentType(desc.Metadata.GUID, desc.ComponentName);

            foreach (var property in desc.Properties)
            {
                componentType.PropertyNames.Add(property.SerializedName);
            }

            var component = new PositionalComponent(componentType);

            component.Layout.Location    = new Point(options.Width / 2 - (options.Horizontal ? options.Size : 0), options.Height / 2 - (!options.Horizontal ? options.Size : 0));
            component.Layout.Orientation = options.Horizontal ? Orientation.Horizontal : Orientation.Vertical;

            // Minimum size
            component.Layout.Size = Math.Max(desc.MinSize, options.Size);

            // Configuration
            if (options.Configuration != null)
            {
                foreach (var setter in options.Configuration.Setters)
                {
                    component.Properties[setter.Key] = setter.Value;
                }
            }

            // Orientation
            FlagOptions flagOptions = desc.DetermineFlags(component);

            if ((flagOptions & FlagOptions.HorizontalOnly) == FlagOptions.HorizontalOnly && component.Layout.Orientation == Orientation.Vertical)
            {
                component.Layout.Orientation = Orientation.Horizontal;
                component.Layout.Size        = desc.MinSize;
            }
            else if ((flagOptions & FlagOptions.VerticalOnly) == FlagOptions.VerticalOnly && component.Layout.Orientation == Orientation.Horizontal)
            {
                component.Layout.Orientation = Orientation.Vertical;
                component.Layout.Size        = desc.MinSize;
            }

            CircuitDocument document = new CircuitDocument();

            document.Elements.Add(component);

            var lookup = new DictionaryComponentDescriptionLookup();

            lookup.AddDescription(componentType, desc);
            var docRenderer = new CircuitRenderer(lookup);

            var buffer = new BufferedDrawingContext();

            docRenderer.RenderCircuit(document, buffer);
            var bb = buffer.BoundingBox;

            T resultContext;
            IDrawingContext dc;

            if (options.Crop)
            {
                resultContext = drawingContext(options.Crop ? bb.Size : new Size(options.Width, options.Height));
                dc            = new TranslationDrawingContext(new Vector(Math.Round(-bb.X), Math.Round(-bb.Y)), resultContext);
            }
            else if (options.Center)
            {
                resultContext = drawingContext(new Size(options.Width, options.Height));

                var x = bb.X - options.Width / 2 + bb.Width / 2;
                var y = bb.Y - options.Height / 2 + bb.Height / 2;
                dc = new TranslationDrawingContext(new Vector(Math.Round(-x), Math.Round(-y)), resultContext);
            }
            else
            {
                resultContext = drawingContext(new Size(options.Width, options.Height));
                dc            = resultContext;
            }

            docRenderer.RenderCircuit(document, dc);

            return(resultContext);
        }
Exemplo n.º 12
0
        public static void SizeComponent(Component component, Point start, Point end)
        {
            // reverse points if necessary
            Point newStart = start;
            Point newEnd   = end;
            bool  switched = false;

            if (start.X < end.X)
            {
                newStart = end;
                newEnd   = start;
                switched = true;
            }

            if (true) // snap to grid
            {
                if (Math.IEEERemainder(newStart.X, 20d) != 0)
                {
                    newStart = newStart.WithNewX(Snap(newStart, GridSize).X);
                }
                if (Math.IEEERemainder(newStart.Y, 20d) != 0)
                {
                    newStart = newStart.WithNewY(Snap(newStart, GridSize).Y);
                }
                if (Math.IEEERemainder(newEnd.X, 20d) != 0)
                {
                    newEnd = newEnd.WithNewX(Snap(newEnd, GridSize).X);
                }
                if (Math.IEEERemainder(newEnd.Y, 20d) != 0)
                {
                    newEnd = newEnd.WithNewY(Snap(newEnd, GridSize).Y);
                }
            }
            if (true) // snap to horizontal or vertical
            {
                double height  = Math.Max(newStart.Y, newEnd.Y) - Math.Min(newStart.Y, newEnd.Y);
                double length  = Math.Sqrt(Math.Pow(newEnd.X - newStart.X, 2d) + Math.Pow(newEnd.Y - newStart.Y, 2d));
                double bearing = Math.Acos(height / length) * (180 / Math.PI);

                if (bearing <= 45 && switched)
                {
                    newStart = newStart.WithNewX(newEnd.X);
                }
                else if (bearing <= 45 && !switched)
                {
                    newEnd = newEnd.WithNewX(newStart.X);
                }
                else if (bearing > 45 && switched)
                {
                    newStart = newStart.WithNewY(newEnd.Y);
                }
                else
                {
                    newEnd = newEnd.WithNewY(newStart.Y);
                }
            }

            if (newStart.X > newEnd.X || newStart.Y > newEnd.Y)
            {
                component.Location = new Vector(newEnd.X, newEnd.Y);
                if (newStart.X == newEnd.X)
                {
                    component.Size        = newStart.Y - newEnd.Y;
                    component.Orientation = Orientation.Vertical;
                }
                else
                {
                    component.Size        = newStart.X - newEnd.X;
                    component.Orientation = Orientation.Horizontal;
                }
            }
            else
            {
                component.Location = new Vector(newStart.X, newStart.Y);
                if (newStart.X == newEnd.X)
                {
                    component.Size        = newEnd.Y - newStart.Y;
                    component.Orientation = Orientation.Vertical;
                }
                else
                {
                    component.Size        = newEnd.X - newStart.X;
                    component.Orientation = Orientation.Horizontal;
                }
            }

            FlagOptions flagOptions = ApplyFlags(component);

            if ((flagOptions & FlagOptions.HorizontalOnly) == FlagOptions.HorizontalOnly && component.Orientation == Orientation.Vertical)
            {
                component.Orientation = Orientation.Horizontal;
                component.Size        = component.Description.MinSize;
            }
            else if ((flagOptions & FlagOptions.VerticalOnly) == FlagOptions.VerticalOnly && component.Orientation == Orientation.Horizontal)
            {
                component.Orientation = Orientation.Vertical;
                component.Size        = component.Description.MinSize;
            }

            component.ImplementMinimumSize(GridSize);
            component.ImplementMinimumSize(component.Description.MinSize);

            component.ResetConnections();
        }
Exemplo n.º 13
0
        public static T RenderPreview <T>(Func <Size, T> drawingContext,
                                          ComponentDescription desc,
                                          PreviewGenerationOptions options)
            where T : IDrawingContext
        {
            var componentType = new TypeDescriptionComponentType(desc.Metadata.GUID, ComponentType.UnknownCollection, desc.ComponentName);

            var component = new PositionalComponent(componentType);

            component.Layout.Location    = new Point(options.Width / 2 - (options.Horizontal ? options.Size : 0), options.Height / 2 - (!options.Horizontal ? options.Size : 0));
            component.Layout.Orientation = options.Horizontal ? Orientation.Horizontal : Orientation.Vertical;

            // Minimum size
            component.Layout.Size = Math.Max(desc.MinSize, options.Size);

            // Configuration
            var configurationDesc = desc.Metadata.Configurations.FirstOrDefault(x => x.Name == options.Configuration);

            if (configurationDesc != null)
            {
                foreach (var setter in configurationDesc.Setters)
                {
                    component.Properties[setter.Key] = setter.Value;
                }
            }

            // Orientation
            FlagOptions flagOptions = desc.DetermineFlags(component);

            if ((flagOptions & FlagOptions.HorizontalOnly) == FlagOptions.HorizontalOnly && component.Layout.Orientation == Orientation.Vertical)
            {
                component.Layout.Orientation = Orientation.Horizontal;
            }
            else if ((flagOptions & FlagOptions.VerticalOnly) == FlagOptions.VerticalOnly && component.Layout.Orientation == Orientation.Horizontal)
            {
                component.Layout.Orientation = Orientation.Vertical;
            }

            // Flip
            if ((flagOptions & FlagOptions.FlipPrimary) == FlagOptions.FlipPrimary && (options.Flip & FlipState.Primary) == FlipState.Primary)
            {
                component.Layout.Flip |= FlipState.Primary;
            }
            if ((flagOptions & FlagOptions.FlipSecondary) == FlagOptions.FlipSecondary && (options.Flip & FlipState.Secondary) == FlipState.Secondary)
            {
                component.Layout.Flip |= FlipState.Secondary;
            }

            // Properties
            foreach (var property in options.Properties)
            {
                // Look up serialized name
                var propertyInfo = desc.Properties.FirstOrDefault(x => x.Name == property.Key);

                if (propertyInfo != null)
                {
                    component.Properties[propertyInfo.SerializedName] = PropertyValue.Dynamic(property.Value);
                }
            }

            foreach (var property in options.RawProperties)
            {
                component.Properties[property.Key] = property.Value;
            }

            CircuitDocument document = new CircuitDocument();

            document.Elements.Add(component);

            var lookup = new DictionaryComponentDescriptionLookup();

            lookup.AddDescription(componentType, desc);
            var docRenderer = new CircuitRenderer(lookup);

            var buffer = new SkiaBufferedDrawingContext();

            docRenderer.RenderCircuit(document, buffer);
            var bb = buffer.BoundingBox ?? new Rect();

            T resultContext;
            IDrawingContext dc;

            Vector translationOffset = new Vector(0, 0);

            if (options.Crop)
            {
                resultContext = drawingContext(options.Crop ? bb.Size : new Size(options.Width * options.Scale, options.Height * options.Scale));
                dc            = new TranslationDrawingContext(new Vector(Math.Round(-bb.X), Math.Round(-bb.Y)), resultContext);
            }
            else if (options.Center)
            {
                resultContext = drawingContext(new Size(options.Width, options.Height));

                var x = bb.X - options.Width / 2 + bb.Width / 2;
                var y = bb.Y - options.Height / 2 + bb.Height / 2;
                translationOffset = new Vector(Math.Round(-x), Math.Round(-y));
                dc = new TranslationDrawingContext(translationOffset, resultContext);
            }
            else
            {
                resultContext = drawingContext(new Size(options.Width, options.Height));
                dc            = resultContext;
            }

            if (options.Grid && resultContext is SkiaDrawingContext gridSkiaContext)
            {
                RenderGrid(gridSkiaContext, options.Width, options.Height, translationOffset);
            }

            if (options.DebugLayout && resultContext is SkiaDrawingContext debugSkiaContext)
            {
                RenderDebugLayout(debugSkiaContext, component, desc, translationOffset);
            }

            docRenderer.RenderCircuit(document, dc);

            return(resultContext);
        }
Exemplo n.º 14
0
        /// <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);
        }