Exemplo n.º 1
0
 public override Lines ConstructContent(ReportTemplateParser parser)
 {
     var lines = new Lines();
     try
     {
         if (Body != null)
         {
             parser.RunFor(Each, In,
                           delegate
                               {
                                   foreach (BasePlainElement element in Body)
                                   {
                                       lines.AddRange(element.ConstructContent(parser));
                                   }
                               });
         }
     }
     catch (ReportTemplateParserException pex)
     {
         lines.Add(new ReportLine(
             new[] {"-+- FOR: " + pex.Reason + " (" + pex.Type + "." + pex.Name + ") -!-" },
             LineAlign.Left, "0", false, false, false, false, -1));
     }
     return lines;
 }
Exemplo n.º 2
0
 public override Lines ConstructContent(ReportTemplateParser parser)
 {
     Lines lines = new Lines();
     int rowNumber = 0;
     if (!Int32.TryParse(Value, out rowNumber))
     {
         if (!Int32.TryParse(parser.Format(Value), out rowNumber))
         {
             rowNumber = 0;
         }
     }
     lines.Add(new ServiceLine(rowNumber));
     return lines;
 }
Exemplo n.º 3
0
 public override Lines ConstructContent(ReportTemplateParser parser)
 {
     var lines = new Lines();
     try
     {
         BasePlainElement[] branch = parser.Check(Condition, Not) ? Then : Else;
         if (branch != null)
         {
             foreach (BasePlainElement element in branch)
             {
                 lines.AddRange(element.ConstructContent(parser));
             }
         }
     }
     catch (ReportTemplateParserException pex)
     {
         lines.Add(new ReportLine(
             new[]{"-+- IF: " + pex.Reason + " (" + pex.Type + "." + pex.Name + ") -!-"},
             LineAlign.Left, "0", false, false, false, false, -1));
     }
     return lines;
 }
Exemplo n.º 4
0
        private void ParseChildNodes(XElement xml, CodeCommentOptions options)
        {
            if (string.Equals(TagName, "code", StringComparison.OrdinalIgnoreCase))
            {
                // Content of code element should be read literally and preserve whitespace.
                using (var reader = xml.CreateReader())
                {
                    reader.MoveToContent();
                    Content = reader.ReadInnerXml();
                }
            }
            else
            {
                // Loop and parse all child nodes.
                var node = xml.FirstNode;
                while (node != null)
                {
                    // If the node is a sub-element, it needs to be handled seperately.
                    if (node.NodeType == XmlNodeType.Element)
                    {
                        var e = (XElement)node;

                        // All root level elements and certain special sub elements always need to
                        // be on their own line.
                        if (e.Parent == null || e.Parent.Parent == null || NewLineElementNames.Contains(e.Name.LocalName, StringComparer.OrdinalIgnoreCase))
                        {
                            CloseInnerText();
                            Lines.Add(new CommentLineXml(e, options));
                        }
                        else
                        {
                            // If the tag is not forced to be on it's own line, append it to the
                            // current content as string.
                            _innerText.Append(CodeCommentHelper.CreateXmlOpenTag(e, options));

                            if (!e.IsEmpty)
                            {
                                if (options.XmlSpaceTagContent)
                                {
                                    _innerText.Append(CodeCommentHelper.Spacer);
                                }

                                ParseChildNodes(e, options);

                                _innerText.Append(CodeCommentHelper.CreateXmlCloseTag(e, options));
                            }
                        }
                    }
                    else
                    {
                        // Always trim trailing
                        var value = node.ToString().TrimEnd(CodeCommentHelper.Spacer);

                        // If the parent is an element, trim the starting spaces.
                        if (node.PreviousNode == null && node.Parent.NodeType == XmlNodeType.Element && !options.XmlSpaceTagContent)
                        {
                            value = value.TrimStart(CodeCommentHelper.Spacer);
                        }

                        // If the previous node was an XML element, put a space before the text
                        // unless the first character is interpunction.
                        if (node.PreviousNode != null && node.PreviousNode.NodeType == XmlNodeType.Element)
                        {
                            if (!StartsWithInterpunction(value))
                            {
                                _innerText.Append(CodeCommentHelper.Spacer);
                            }
                        }

                        _innerText.Append(value);

                        // Add spacing after (almost) each word.
                        if (node.NextNode != null || node.Parent.NodeType != XmlNodeType.Element || options.XmlSpaceTagContent)
                        {
                            _innerText.Append(CodeCommentHelper.Spacer);
                        }
                    }

                    node = node.NextNode;
                }
            }
        }
Exemplo n.º 5
0
    public void Update()
    {
        Default.MeshSphere.Draw(Default.MaterialUnlit, Matrix.TS(center, 0.06f), Color.HSV(0.16f, 0.4f, 0.9f));
        for (int i = 0; i < bodies.Length; i++)
        {
            Vec3 force = (bodies[i].position - center) * -200;

            // Make hands have mass
            for (int h = 0; h < (int)Handed.Max; h++)
            {
                Hand hand = Input.Hand((Handed)h);
                if (!hand.IsTracked)
                {
                    continue;
                }

                Vec3 dir = hand.palm.position - bodies[i].position;
                force += dir.Normalized * 300 * hand.gripActivation;
            }

            for (int t = 0; t < bodies.Length; t++)
            {
                if (i == t)
                {
                    continue;
                }

                Vec3 dir       = bodies[t].position - bodies[i].position;
                Vec3 currForce = dir.Normalized * ((dir.MagnitudeSq * 50) / bodies[i].mass);
                force += currForce;
            }

            if (force.MagnitudeSq > 1)
            {
                force.Normalize();
            }
            bodies[i].force = force;
        }
        for (int i = 0; i < bodies.Length; i++)
        {
            bodies[i].velocity += bodies[i].force * (Time.Elapsedf / bodies[i].mass);
            if (bodies[i].velocity.MagnitudeSq > 1)
            {
                bodies[i].velocity.Normalize();
            }
            bodies[i].position += bodies[i].velocity * Time.Elapsedf;

            Color col = bodies[i].color * Math.Min(0.5f, (bodies[i].position - center).MagnitudeSq / 0.5f);
            col.a = 1;
            if (trailId == i)
            {
                bodies[i].trail.Add(new LinePoint(bodies[i].position, col, 0.02f));
                if (bodies[i].trail.Count > 1000)
                {
                    bodies[i].trail.RemoveAt(0);
                }
            }
            else if (bodies[i].trail.Count > 0)
            {
                bodies[i].trail[bodies[i].trail.Count - 1] = new LinePoint(bodies[i].position, col, 0.02f);
            }
            Default.MeshSphere.Draw(Default.Material, Matrix.TS(bodies[i].position, 0.03f * bodies[i].mass), col);
            Lines.Add(bodies[i].trail.ToArray());
        }
        trailId = (trailId + 1) % bodies.Length;
    }
Exemplo n.º 6
0
        private void InsertLines(List <string> toInsert, string currentdir)
        {
            uint curline = 1;
            bool in_comment = false, in_asm = false;

            IsLoaded = true;

            for (int i = 0; i < toInsert.Count; i++, curline++)
            {
                string scriptline = Helper.trim(toInsert[i]);
                bool   nextline   = false;
                int    curpos     = 0; // for skipping string literals

                while (!nextline)
                {
                    // Handle comments and string literals
                    int linecmt = -1, spancmt = -1, strdel = -1;

                    if (curpos < scriptline.Length)
                    {
                        if (in_comment)
                        {
                            spancmt = 0;
                        }
                        else
                        {
                            int min = -1, tmp;
                            tmp = scriptline.IndexOf("//", curpos);
                            if (tmp < min)
                            {
                                min = linecmt = tmp;
                            }
                            tmp = scriptline.IndexOf(';', curpos);
                            if (tmp < min)
                            {
                                min = linecmt = tmp;
                            }
                            tmp = scriptline.IndexOf("/*", curpos);
                            if (tmp < min)
                            {
                                min = spancmt = tmp;
                            }
                            tmp = scriptline.IndexOf('\"', curpos);
                            if (tmp < min)
                            {
                                min = strdel = tmp;
                            }

                            curpos = min;

                            if (linecmt != min)
                            {
                                linecmt = -1;
                            }
                            if (spancmt != min)
                            {
                                spancmt = -1;
                            }
                            if (strdel != min)
                            {
                                strdel = -1;
                            }
                        }
                    }

                    if (strdel >= 0)
                    {
                        curpos = scriptline.IndexOf('\"', strdel + 1); // find end of string
                        if (curpos >= 0)
                        {
                            curpos++;
                        }
                    }
                    else if (linecmt >= 0)
                    {
                        scriptline = scriptline.Remove(linecmt);
                    }
                    else if (spancmt >= 0)
                    {
                        int start = in_comment ? spancmt : spancmt + 2;
                        int end   = scriptline.IndexOf("*/", start);
                        in_comment = (end < 0);
                        if (in_comment)
                        {
                            scriptline = scriptline.Remove(spancmt);
                        }
                        else
                        {
                            scriptline = scriptline.Remove(spancmt) + scriptline.Substring(end - spancmt + 2);
                        }
                    }
                    else
                    {
                        scriptline = Helper.trim(scriptline);
                        int len = scriptline.Length;

                        if (len != 0)
                        {
                            string lcline = scriptline.ToLowerInvariant();

                            // Check for label
                            if (!in_asm && len > 1 && scriptline[len - 1] == ':')
                            {
                                scriptline = scriptline.Remove(len - 1);
                                Labels[Helper.trim(scriptline)] = (uint)(Lines.Count);
                            }
                            // Check for #inc and include file if it exists
                            else if (0 == lcline.IndexOf("#inc"))
                            {
                                if (len > 5 && Char.IsWhiteSpace(lcline[4]))
                                {
                                    string args = Helper.trim(scriptline.Substring(5));
                                    if (args.Length > 2 && args[0] == '\"' && args.EndsWith("\""))
                                    {
                                        string dir;
                                        string philename = Helper.pathfixup(args.Substring(1, args.Length - 2), false);
                                        if (!Helper.IsFullPath(philename))
                                        {
                                            philename = currentdir + philename;
                                            dir       = currentdir;
                                        }
                                        else
                                        {
                                            dir = Helper.folderfrompath(philename);
                                        }

                                        InsertLines(Helper.ReadLinesFromFile(philename), dir);
                                    }
                                    else
                                    {
                                        interpreter.Host.MsgError("Bad #inc directive!");
                                    }
                                }
                                else
                                {
                                    this.interpreter.Host.MsgError("Bad #inc directive!");
                                }
                            }
                            // Logging
                            else if (!in_asm && lcline == "#log")
                            {
                                Log = true;
                            }
                            // Add line
                            else
                            {
                                Line cur = new Line();

                                if (in_asm && lcline == "ende")
                                {
                                    in_asm = false;
                                }

                                cur.RawLine    = scriptline;
                                cur.LineNumber = curline;
                                cur.IsCommand  = !in_asm;

                                if (!in_asm && lcline == "exec")
                                {
                                    in_asm = true;
                                }

                                ParseArgumentsIntoLine(scriptline, cur);

                                Lines.Add(cur);
                            }
                        }
                        nextline = true;
                    }
                }
            }
        }
Exemplo n.º 7
0
        public void Step()
        {
            const float shoulderWidth = 0.16f;             // half the total shoulder width
            const float forearm       = 0.22f;             // length of the forearm
            const float uarm          = 0.25f;             // length of the upper arm
            const float headLength    = 0.1f;              // length from head point to neck
            const float neckLength    = 0.02f;             // length from neck to center shoulders
            const float shoulderDrop  = 0.05f;             // shoulder drop height from shoulder center
            const float elbowFlare    = 0.45f;             // Elbows point at a location 1m down, and elbowFlare out from the shoulder

            Pose head = Input.Head;

            // Head, neck, and shoulder center
            headLine[0].pt = head.position;
            headLine[1].pt = headLine[0].pt + head.orientation * V.XYZ(0, -headLength, 0);
            headLine[2].pt = headLine[1].pt - V.XYZ(0, neckLength, 0);
            headLine[0].pt = Vec3.Lerp(headLine[0].pt, headLine[1].pt, 0.1f);
            Lines.Add(headLine);

            // Shoulder forward facing direction is head direction weighted
            // equally with the direction of both hands.
            Vec3 forward =
                head.Forward.X0Z.Normalized * 2
                + (Input.Hand(Handed.Right).wrist.position - headLine[2].pt.X0Z).Normalized
                + (Input.Hand(Handed.Left).wrist.position - headLine[2].pt.X0Z).Normalized;

            forward = forward * 0.25f;
            Vec3 right = Vec3.PerpendicularRight(forward, Vec3.Up).Normalized;

            // Now for each arm
            for (int h = 0; h < 2; h++)
            {
                float handed  = h == 0 ? -1 : 1;
                Hand  hand    = Input.Hand((Handed)h);
                Vec3  handPos = hand.wrist.position;
                if (!hand.IsTracked)
                {
                    continue;
                }

                armLine[0].pt = headLine[2].pt;
                armLine[1].pt = armLine[0].pt + right * handed * shoulderWidth - Vec3.Up * shoulderDrop;
                armLine[3].pt = handPos;

                // Triangle represented by 3 edges, forearm, uarm, and armDist
                float armDist = Math.Min(forearm + uarm, Vec3.Distance(armLine[1].pt, handPos));

                // Heron's formula to find area
                float s    = (forearm + uarm + armDist) / 2;
                float area = SKMath.Sqrt(s * (s - forearm) * (s - uarm) * (s - armDist));
                // Height of triangle based on area
                float offsetH = (2 * area) / armDist;
                // Height can now be used to calculate how far off the elbow is
                float offsetD = SKMath.Sqrt(Math.Abs(offsetH * offsetH - uarm * uarm));

                // Elbow calculation begins somewhere along the line between the
                // shoulder and the wrist.
                Vec3 dir = (handPos - armLine[1].pt).Normalized;
                Vec3 at  = armLine[1].pt + dir * offsetD;
                // The elbow naturally flares out to the side, rather than
                // dropping straight down. Here, we find a point to flare out
                // towards.
                Vec3  flarePoint = headLine[2].pt + right * handed * elbowFlare - Vec3.Up;
                Plane flarePlane = new Plane(flarePoint, Ray.FromTo(headLine[2].pt, handPos).Closest(flarePoint) - flarePoint);
                Vec3  dirDown    = (flarePlane.Closest(at) - at).Normalized;
                armLine[2].pt = at + dirDown * offsetH;

                Lines.Add(armLine);
                for (int i = 1; i < 5; i++)
                {
                    Lines.Add(handPos, hand[(FingerId)i, JointId.KnuckleMajor].position, Color32.White, new Color32(255, 255, 255, 0), 0.01f);
                }
            }
        }
Exemplo n.º 8
0
        public void add(string type, Node node, Line line, Position position = null, int layer = 0)
        {
            Nodes nodes = new Nodes();
            if (node != null)
            {
                nodes.Add(new Node(node));
            }

            Lines lines = new Lines();
            if (line != null)
            {
                lines.Add(new Line(line));
            }
            this.add(type, nodes, lines, position, layer);
        }
Exemplo n.º 9
0
        // get all lines for all children nodes
        public Lines getAllSubNodeLines(Node node)
        {
            Lines lines = new Lines();

            if (node.haslayer)
            {
                Layer layer = this.getLayer(node.id);

                foreach (Line line in layer.lines)
                {
                    lines.Add(line);
                }

                foreach (Node subNode in layer.nodes)
                {
                    if (node.haslayer)
                    {
                        Lines sublines = this.getAllSubNodeLines(subNode);

                        foreach (Line line in sublines)
                        {
                            lines.Add(line);
                        }
                    }
                }
            }

            return lines;
        }
Exemplo n.º 10
0
        // NODE get lines which are connected with current selected nodes
        public Lines getSelectedLines()
        {
            Lines SelectedLinesTemp = new Lines();
            int id = 0;

            foreach (Node srec in this.selectedNodes) {
                id = srec.id;
                foreach (Line lin in this.diagram.layers.getAllLines()) {
                    if (lin.start == id) {
                        SelectedLinesTemp.Add(lin);
                    }
                }
            }

            Lines SelectedLines = new Lines();

            foreach (Line lin in SelectedLinesTemp)
            {
                id = lin.end;
                foreach (Node srec in this.selectedNodes)
                {
                    if (id == srec.id)
                    {
                        SelectedLines.Add(lin);
                    }
                }
            }

            return SelectedLines;
        }
Exemplo n.º 11
0
 public void AddLine(string line)
 {
     Lines.Add(line);
 }
Exemplo n.º 12
0
 public override Lines ConstructContent(ReportTemplateParser parser)
 {
     var lines = new Lines();
     if (parser.Check(Condition, Not))
     {
         if (Columns == null || Columns.Length <= 0)
         {
             var text = new[]
             {
                 parser.Format(LinePart.ConstructLine(parser, Part, Text ?? String.Empty))
             };
             if (!string.IsNullOrEmpty(SplitChar))
             {
                 text = text[0].Split(SplitChar.ToCharArray());
             }
             foreach (string s in text)
             {
                 lines.Add(
                     new ReportLine(new[] {NeedTrim ? s.Trim() : s},
                                    Align ?? LineAlign.Left,
                                    FontSize, IsBold, IsItalic, false, false, IsLineDotted));
             }
         }
         else
         {
             var columns = new ArrayList();
             foreach (LinePart t in Columns)
             {
                 if (parser.Check(t.Condition, t.Not))
                 {
                     if (t.In != null && t.Each != null)
                     {
                         parser.RunFor(t.Each, t.In,
                                       () => columns.Add(parser.Format(
                                           LinePart.ConstructLine
                                               (parser, t.Part, t.Text ?? String.Empty))));
                     }
                     else
                     {
                         columns.Add(parser.Format(
                             LinePart.ConstructLine(parser, t.Part, t.Text ?? String.Empty)));
                     }
                 }
             }
             var arr = new string[columns.Count];
             columns.CopyTo(arr);
             lines.Add(new ReportLine(arr,
                                      Align ?? LineAlign.Left,
                                      FontSize, IsBold, IsItalic, NewPage, ResetPageNumber, IsLineDotted));
         }
     }
     return lines;
 }
Exemplo n.º 13
0
        // EVENT Mouse Up                                                                              // [MOUSE] [UP] [EVENT]
        public void DiagramApp_MouseUp(object sender, MouseEventArgs e)
        {
            #if DEBUG
            this.logEvent("MouseUp");
            #endif

            this.actualMousePos.set(e.X, e.Y);
            Position mouseTranslation = new Position(this.actualMousePos).subtract(this.startMousePos);

            // States
            bool mousemove = ((this.actualMousePos.x != this.startMousePos.x) || (this.actualMousePos.y != this.startMousePos.y)); // mouse change position
            bool buttonleft = e.Button == MouseButtons.Left;
            bool buttonright = e.Button == MouseButtons.Right;
            bool buttonmiddle = e.Button == MouseButtons.Middle;
            bool isreadonly = this.diagram.options.readOnly;
            bool keyalt = this.keyalt;
            bool keyctrl = this.keyctrl;
            bool keyshift = this.keyshift;
            bool dblclick = this.stateDblclick;
            bool finishdraging = this.stateDragSelection;
            bool finishadding = this.stateAddingNode;
            bool finishselecting = mousemove && this.stateSelectingNodes;

            MoveTimer.Enabled = false;

            if(dblclick)
            {
                this.stateSelectingNodes = false;
            }
            else
            // KEY DRAG
            if (finishdraging) // drag node
            {
                if (!this.diagram.options.readOnly)
                {
                    if (this.sourceNode != null && !keyctrl) // return node to starting position after connection is created
                    {
                        Position translation = new Position(this.startNodePos)
                            .subtract(sourceNode.position);

                        if (this.selectedNodes.Count > 0)
                        {
                            foreach (Node node in this.selectedNodes)
                            {
                                node.position.add(translation);
                            }
                        }

                        this.diagram.InvalidateDiagram();
                    }
                }
            }
            else
            // KEY DRAG-MMIDDLE
            if (finishadding)
            {
                this.diagram.InvalidateDiagram();
            }
            else
            // KEY DRAG+MLEFT select nodes with selection rectangle
            if (finishselecting)
            {
                if (mousemove)
                {
                    Position a = new Position(this.startMousePos)
                        .scale(this.scale)
                        .add(this.shift)
                        .subtract(this.startShift);

                    Position b = new Position(this.actualMousePos)
                        .scale(this.scale);

                    int temp;
                    if (b.x < a.x) { temp = a.x; a.x = b.x; b.x = temp; }
                    if (b.y < a.y) { temp = b.y; b.y = a.y; a.y = temp; }

                    if (!this.keyshift) this.ClearSelection();
                    foreach (Node rec in this.currentLayer.nodes)
                    {
                        if (
                            (rec.layer == this.currentLayer.id || rec.id == this.currentLayer.id)
                            && -this.shift.x + a.x <= rec.position.x
                            && rec.position.x + rec.width <= -this.shift.x + b.x
                            && -this.shift.y + a.y <= rec.position.y
                            && rec.position.y + rec.height <= -this.shift.y + b.y) // get all nodes in selection rectangle
                        {
                            if (keyshift && !keyctrl && !keyalt) // KEY SHIFT+MLEFT Invert selection
                            {
                                if (rec.selected)
                                {
                                    this.RemoveNodeFromSelection(rec);
                                }
                                else
                                {
                                    this.SelectNode(rec);
                                }
                            }

                            if (!keyshift && !keyctrl && !keyalt) // KEY MLEFT select nodes
                            {
                                this.SelectNode(rec);
                            }
                        }
                    }

                    this.diagram.InvalidateDiagram();
                }
            }

            Node TargetNode = this.findNodeInMousePosition(new Position(e.X, e.Y));

            if (buttonleft) // MLEFT
            {

                if (!keyalt && keyctrl && !keyshift && TargetNode != null && TargetNode.selected) // CTRL+CLICK add node to selection
                {
                    this.RemoveNodeFromSelection(TargetNode);
                    this.diagram.InvalidateDiagram();
                }
                else
                if (!keyalt && keyctrl && !keyshift && TargetNode != null && !TargetNode.selected) // CTRL+CLICK remove node from selection
                {
                    this.SelectNode(TargetNode);
                    this.diagram.InvalidateDiagram();
                }
                else
                if (this.stateCoping && mousemove) // CTRL+DRAG copy part of diagram
                {
                    this.stateCoping = false;

                    DiagramBlock newBlock = this.diagram.duplicatePartOfDiagram(this.selectedNodes, this.currentLayer.id);

                    Position vector = new Position(this.actualMousePos)
                        .scale(this.scale)
                        .subtract(this.vmouse)
                        .subtract(this.shift)
                        .subtract(this.sourceNode.position);

                    // filter only top nodes fromm all new created nodes. NewNodes containing sublayer nodes.
                    Nodes topNodes = new Nodes();

                    foreach (Node node in newBlock.nodes)
                    {
                        if (node.layer == this.currentLayer.id)
                        {
                            topNodes.Add(node);
                        }
                    }

                    foreach (Node node in topNodes)
                    {
                        node.position.add(vector);
                    }

                    this.diagram.unsave("create", newBlock.nodes, newBlock.lines);

                    this.SelectNodes(topNodes);

                    this.diagram.unsave();
                    this.diagram.InvalidateDiagram();
                }
                else
                if (bottomScrollBar != null
                    && rightScrollBar != null
                    && (bottomScrollBar.MouseUp() || rightScrollBar.MouseUp()))
                {
                    this.diagram.InvalidateDiagram();
                }
                else
                // KEY MLEFT clear selection
                if (!mousemove
                    && TargetNode == null
                    && this.sourceNode == null
                    && this.selectedNodes.Count() > 0
                    && !keyalt
                    && !keyctrl
                    && !keyshift)
                {
                    this.ClearSelection();
                    this.diagram.InvalidateDiagram();
                }
                else
                // KEY CTRL+ALT+DRAG create node and conect with existing node
                if (!isreadonly
                    && !keyshift
                    && keyctrl
                    && keyalt
                    && TargetNode == null
                    && this.sourceNode != null)
                {
                    var s = this.sourceNode;
                    var node = this.CreateNode(new Position(e.X, e.Y));
                    node.shortcut = s.id;
                    this.diagram.Connect(s, node);
                    this.diagram.unsave("create", node, this.shift, this.currentLayer.id);
                    this.diagram.InvalidateDiagram();
                }
                else
                // KEY CTRL+ALT+DRAG create shortcut beetwen objects
                if (!isreadonly
                    && !keyshift
                    && keyctrl
                    && keyalt
                    && TargetNode != null
                    && this.sourceNode != null
                    && TargetNode != this.sourceNode)
                {
                    this.diagram.unsave("edit", this.sourceNode, this.shift, this.currentLayer.id);
                    this.sourceNode.link = "#" + TargetNode.id.ToString();
                    this.diagram.unsave();
                    this.diagram.InvalidateDiagram();
                }
                else
                // KEY DRAG move node
                if
                (
                    !isreadonly
                    && (
                        (TargetNode == null && this.sourceNode != null)
                        || (
                            TargetNode != null
                            && this.sourceNode != TargetNode
                            && TargetNode.selected
                        )
                        || (TargetNode != null && this.sourceNode == TargetNode)
                    )
                    && Math.Sqrt(mouseTranslation.x * mouseTranslation.x + mouseTranslation.y * mouseTranslation.y) > 5
                )
                {
                    Position vector = new Position(this.actualMousePos)
                        .scale(this.scale)
                        .subtract(this.vmouse)
                        .subtract(this.shift)
                        .subtract(this.sourceNode.position);

                    if (this.selectedNodes.Count > 0)
                    {
                        this.diagram.undoOperations.add("edit", this.selectedNodes, null, this.shift, this.currentLayer.id);

                        foreach (Node node in this.selectedNodes)
                        {
                            node.position.add(vector);
                        }

                        this.diagram.unsave();
                    }

                    this.diagram.InvalidateDiagram();
                }
                else
                // KEY DRAG+CTRL create node and conect with existing node
                if (!isreadonly
                    && !keyshift
                    && !keyctrl
                    && keyalt
                    && TargetNode != null
                    && this.sourceNode == null)
                {
                    Node node = this.CreateNode(
                            new Position(
                                +this.shift.x - startShift.x + this.startMousePos.x,
                                +this.shift.y - startShift.y + this.startMousePos.y
                            )
                        );

                    Line line = this.diagram.Connect(
                        node,
                        TargetNode
                    );

                    this.diagram.unsave("create", node, line, this.shift, this.currentLayer.id);
                    this.diagram.InvalidateDiagram();
                }
                else
                // KEY CTRL+ALT+DRAG create node and make shortcut to target node
                if (!isreadonly
                    && keyalt
                    && keyctrl
                    && !keyshift
                    && TargetNode != null
                    && this.sourceNode == null)
                {
                    Node newrec = this.CreateNode(
                        new Position(this.shift).subtract(startShift).add(this.startMousePos)
                    );

                    newrec.link = "#" + TargetNode.id;
                    this.diagram.unsave("create", newrec, this.shift, this.currentLayer.id);
                    this.diagram.InvalidateDiagram();
                }
                else
                // KEY DBLCLICK open link or edit window after double click on node [dblclick] [open] [edit]
                if (dblclick
                    && this.sourceNode != null
                    && !keyctrl
                    && !keyalt
                    && !keyshift)
                {
                    this.resetStates();
                    this.OpenLinkAsync(this.sourceNode);
                }
                else
                // KEY SHIFT+DBLCLICK open node edit form
                if (dblclick
                    && this.sourceNode != null
                    && !keyctrl
                    && !keyalt
                    && keyshift)
                {
                    this.diagram.EditNode(this.sourceNode);
                }
                else
                // KEY CTRL+DBLCLICK open link in node
                if (dblclick
                    && this.sourceNode != null
                    && keyctrl
                    && !keyalt
                    && !keyshift)
                {
                    if (this.sourceNode.link != "")
                    {
                        Os.openPathInSystem(this.sourceNode.link);
                    }
                }
                else
                // KEY DBLCLICK+SPACE change position in zoom view mode
                if (this.stateZooming
                    && dblclick
                    && !keyctrl
                    && !keyalt
                    && !keyshift)
                {
                    this.shift
                        .subtract(
                            this.actualMousePos
                            .clone()
                            .scale(this.scale)
                            )
                        .add(
                            (this.ClientSize.Width * this.scale) / 2,
                            (this.ClientSize.Height * this.scale) / 2
                        );
                    this.diagram.InvalidateDiagram();
                }
                else
                // KEY CTRL+SHIFT+MLEFT conect with selected nodes new node or selected node
                if (!isreadonly
                    && keyshift
                    && keyctrl
                    && this.selectedNodes.Count() > 0
                    && e.X == this.startMousePos.x
                    && e.Y == this.startMousePos.y)
                {
                    // TODO Still working this?
                    Node newrec = TargetNode;

                    Nodes newNodes = new Nodes();
                    if (newrec == null)
                    {
                        newrec = this.CreateNode(this.actualMousePos.clone().subtract(10), false);
                        newNodes.Add(newrec);
                    }

                    Lines newLines = new Lines();
                    foreach (Node rec in this.selectedNodes)
                    {
                        Line line = this.diagram.Connect(rec, newrec);
                        newLines.Add(line);
                    }

                    this.SelectOnlyOneNode(newrec);
                    this.diagram.unsave("create", newNodes, newLines, this.shift, this.currentLayer.id);
                }
                else
                // KEY ALT+MLEFT
                // KEY DBLCLICK create new node
                if (!isreadonly
                    && (dblclick || keyalt)
                    && !keyshift
                    && !keyctrl
                    && TargetNode == null
                    && this.sourceNode == null
                    && e.X == this.startMousePos.x
                    && e.Y == this.startMousePos.y)
                {
                    Node newNode = this.CreateNode(this.actualMousePos.clone().subtract(10), false);
                    this.diagram.unsave("create", newNode, this.shift, this.currentLayer.id);
                }
                else
                // KEY DRAG+ALT copy style from node to other node
                if (!isreadonly
                    && !keyshift
                    && !keyctrl
                    && keyalt
                    && TargetNode != null
                    && this.sourceNode != null
                    && this.sourceNode != TargetNode)
                {
                    if (this.selectedNodes.Count() > 1)
                    {
                        this.diagram.undoOperations.add("edit", this.selectedNodes, null, this.shift, this.currentLayer.id);
                        foreach (Node rec in this.selectedNodes)
                        {
                            rec.copyNodeStyle(TargetNode);
                        }
                        this.diagram.unsave();
                    }

                    if (this.selectedNodes.Count() == 1
                        || (this.selectedNodes.Count() == 0 && this.sourceNode != null))
                    {
                        this.diagram.undoOperations.add("edit", TargetNode, this.shift, this.currentLayer.id);

                        TargetNode.copyNodeStyle(this.sourceNode);

                        if (this.selectedNodes.Count() == 1 && this.selectedNodes[0] != this.sourceNode)
                        {
                            this.ClearSelection();
                            this.SelectNode(this.sourceNode);
                        }
                        this.diagram.unsave();
                    }
                }
                else
                // KEY DRAG make link between two nodes
                if (!isreadonly
                    && !keyctrl
                    && !keyalt
                    && TargetNode != null
                    && this.sourceNode != null
                    && this.sourceNode != TargetNode)
                {
                    bool arrow = false;
                    if (keyshift)
                    {
                        arrow = true;
                    }

                    Lines newLines = new Lines();
                    Lines removeLines = new Lines();
                    if (this.selectedNodes.Count() > 0)
                    {
                        foreach (Node rec in this.selectedNodes)
                        {
                            if (rec != TargetNode)
                            {
                                if (this.diagram.hasConnection(rec, TargetNode))
                                {
                                    Line removeLine = this.diagram.getLine(rec, TargetNode);
                                    removeLines.Add(removeLine);
                                    this.diagram.Disconnect(rec, TargetNode);

                                }
                                else
                                {
                                    Line newLine = this.diagram.Connect(rec, TargetNode, arrow, null);
                                    newLines.Add(newLine);
                                }
                            }
                        }
                    }

                    if (newLines.Count() > 0 && removeLines.Count() > 0)
                    {
                        this.diagram.undoOperations.startGroup();
                        this.diagram.undoOperations.add("create", null, newLines, this.shift, this.currentLayer.id);
                        this.diagram.undoOperations.add("delete", null, removeLines, this.shift, this.currentLayer.id);
                        this.diagram.undoOperations.endGroup();
                        this.diagram.unsave();
                    }
                    else if (newLines.Count() > 0)
                    {
                        this.diagram.undoOperations.add("create", null, newLines, this.shift, this.currentLayer.id);
                    }
                    else if (removeLines.Count() > 0)
                    {
                        this.diagram.undoOperations.add("delete", null, removeLines, this.shift, this.currentLayer.id);
                    }

                    this.diagram.InvalidateDiagram();
                }
                // KEY SHIFT+MLEFT add node to selected nodes
                else
                if (!keyctrl
                    && keyshift
                    && !keyalt
                    && this.sourceNode == TargetNode
                    && TargetNode != null
                    && !TargetNode.selected)
                {
                    this.SelectNode(TargetNode);
                    this.diagram.InvalidateDiagram();
                }
                // KEY SHIFT+MLEFT remove node from selected nodes
                else
                if (!keyctrl
                    && keyshift
                    && !keyalt
                    && TargetNode != null
                    && (this.sourceNode == TargetNode || TargetNode.selected))
                {
                    this.RemoveNodeFromSelection(TargetNode);
                    this.diagram.InvalidateDiagram();
                }
                else
                if (this.sourceNode == TargetNode
                    && this.stateSourceNodeAlreadySelected)
                {
                    this.rename();
                }

            }
            else
            if (buttonright) // KEY MRIGHT
            {
                this.stateMoveView = false; // show popup menu
                if (e.X == this.startMousePos.x
                    && e.Y == this.startMousePos.y
                    && this.startShift.x == this.shift.x
                    && this.startShift.y == this.shift.y)
                {
                    Node temp = this.findNodeInMousePosition(new Position(e.X, e.Y));

                    if (temp == null || (this.sourceNode != temp && !temp.selected))
                    {
                        this.ClearSelection();
                        this.SelectOnlyOneNode(temp);
                    }

                    this.diagram.InvalidateDiagram();
                    PopupMenu.Show(this.Left + e.X, this.Top + e.Y); // [POPUP] show popup
                }
                else { // KEY DRAG+MRIGHT move view
                    this.shift.x = (int)(this.startShift.x + (e.X - this.startMousePos.x) * this.scale);
                    this.shift.y = (int)(this.startShift.y + (e.Y - this.startMousePos.y) * this.scale);
                    this.diagram.InvalidateDiagram();
                }
            }
            else
            if (buttonmiddle) // MMIDDLE
            {
                // KEY DRAG+MMIDDLE conect two existing nodes
                if (this.sourceNode != null && TargetNode != null) {

                    Line newLine = this.diagram.Connect(
                        sourceNode,
                        TargetNode
                    );

                    if (newLine != null) {
                        this.diagram.unsave("create", newLine, this.shift, this.currentLayer.id);
                        this.diagram.InvalidateDiagram();
                    }
                }
                else
                // KEY DRAG+MMIDDLE connect exixting node with new node
                if (this.sourceNode != null && TargetNode == null)
                {

                    Node newNode = this.CreateNode(this.actualMousePos.clone().subtract(10));

                    Line newLine = this.diagram.Connect(
                        sourceNode,
                        newNode
                    );

                    this.diagram.unsave("create", newNode, newLine, this.shift, this.currentLayer.id);
                    this.diagram.InvalidateDiagram();
                }
                else
                // KEY DRAG+MMIDDLE create new node and conect id with existing node
                if (!isreadonly && TargetNode != null)
                {
                    Node newNode = this.CreateNode(
                        (new Position(this.shift)).subtract(this.startShift).add(this.startMousePos)
                    );

                    Line newLine = this.diagram.Connect(
                        newNode,
                        TargetNode
                    );

                    this.diagram.unsave("create", newNode, newLine, this.shift, this.currentLayer.id);
                    this.diagram.InvalidateDiagram();
                }
                else
                // KEY DRAG+MMIDDLE create new node and conect with new node (create line)
                if (!isreadonly && TargetNode == null)
                {
                    Nodes nodes = new Nodes();
                    Lines lines = new Lines();

                    Node node1 = this.CreateNode(
                            (new Position(this.shift)).subtract(this.startShift).add(this.startMousePos),
                            false
                        );

                    nodes.Add(node1);

                    Node node2 = this.CreateNode(
                        this.actualMousePos.clone().subtract(10)
                    );

                    nodes.Add(node2);

                    lines.Add(this.diagram.Connect(
                        node1,
                        node2
                    ));

                    this.diagram.unsave("create", nodes, lines, this.shift, this.currentLayer.id);
                    this.diagram.InvalidateDiagram();
                }
            }

            this.resetStates();
        }
Exemplo n.º 14
0
        public DiagramBlock duplicatePartOfDiagram(Nodes nodes, int layer = 0)
        {
            // get part of diagram for duplicate
            DiagramBlock diagramPart = this.getPartOfDiagram(nodes);

            List<MappedNode> maps = new List<MappedNode>();

            Nodes duplicatedNodes = new Nodes();
            foreach (Node node in diagramPart.nodes)
            {
                duplicatedNodes.Add(node.clone());
            }

            // order nodes parent first (layer must exist when sub node is created)
            Nodes NewReorderedNodes = new Nodes();
            this.nodesReorderNodes(layer, null, duplicatedNodes, NewReorderedNodes);

            int layerParent = 0;

            MappedNode mappedNode;
            Nodes createdNodes = new Nodes();
            Node newNode = null;
            int oldId = 0;
            foreach (Node rec in NewReorderedNodes)
            {
                layerParent = layer;

                // find layer id for sub layer
                foreach (MappedNode mapednode in maps)
                {
                    if (rec.layer == mapednode.oldId)
                    {
                        layerParent = mapednode.newNode.id;
                        break;
                    }
                }

                rec.layer = layerParent;
                rec.resize();

                oldId = rec.id;
                newNode = this.createNode(rec);

                if (newNode != null)
                {
                    mappedNode = new MappedNode();
                    mappedNode.oldId = oldId;
                    mappedNode.newNode = newNode;
                    createdNodes.Add(newNode);
                    maps.Add(mappedNode);
                }
            }

            // fix layers and shortcuts
            foreach (Node rec in duplicatedNodes)
            {
                if (rec.shortcut != 0)
                {
                    foreach (MappedNode mapednode in maps)
                    {
                        if (rec.shortcut == mapednode.oldId)
                        {
                            rec.shortcut = mapednode.newNode.id;
                            break;
                        }
                    }
                }
            }

            Lines createdLines = new Lines();
            Line newLine = null;
            foreach (Line line in diagramPart.lines)
            {
                foreach (MappedNode mapbegin in maps)
                {
                    if (line.start == mapbegin.oldId)
                    {
                        foreach (MappedNode mapend in maps)
                        {
                            if (line.end == mapend.oldId)
                            {
                                // create new line by connecting new nodes
                                newLine = this.Connect(
                                    mapbegin.newNode,
                                    mapend.newNode,
                                    line.arrow,
                                    line.color,
                                    line.width
                                );

                                if (newLine != null) // skip invalid lines (perent not exist)
                                {
                                    createdLines.Add(newLine);
                                }
                            }
                        }
                    }
                }
            }

            return new DiagramBlock(createdNodes, createdLines);
        }
Exemplo n.º 15
0
        /*************************************************************************************************************************/
        // CLIPBOARD
        // paste part of diagram from clipboard
        public DiagramBlock AddDiagramPart(string DiagramXml, Position position, int layer)
        {
            Nodes NewNodes = new Nodes();
            Lines NewLines = new Lines();

            XmlReaderSettings xws = new XmlReaderSettings();
            xws.CheckCharacters = false;

            string xml = DiagramXml;

            try
            {
                using (XmlReader xr = XmlReader.Create(new StringReader(xml), xws))
                {

                    XElement root = XElement.Load(xr);
                    foreach (XElement diagram in root.Elements())
                    {
                        if (diagram.HasElements)
                        {

                            if (diagram.Name.ToString() == "rectangles")
                            {
                                foreach (XElement block in diagram.Descendants())
                                {

                                    if (block.Name.ToString() == "rectangle")
                                    {
                                        Node R = new Node();
                                        R.font = this.FontDefault;

                                        foreach (XElement el in block.Descendants())
                                        {
                                            try
                                            {
                                                if (el.Name.ToString() == "id")
                                                {
                                                    R.id = Int32.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "text")
                                                {
                                                    R.name = el.Value;
                                                }

                                                if (el.Name.ToString() == "note")
                                                {
                                                    R.note = el.Value;
                                                }

                                                if (el.Name.ToString() == "x")
                                                {
                                                    R.position.x = Int32.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "y")
                                                {
                                                    R.position.y = Int32.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "color")
                                                {
                                                    R.color.set(el.Value.ToString());
                                                }

                                                if (el.Name.ToString() == "timecreate")
                                                {
                                                    R.timecreate = el.Value;
                                                }

                                                if (el.Name.ToString() == "timemodify")
                                                {
                                                    R.timemodify = el.Value;
                                                }

                                                if (el.Name.ToString() == "font")
                                                {
                                                    R.font = Fonts.XmlToFont(el);
                                                }

                                                if (el.Name.ToString() == "fontcolor")
                                                {
                                                    R.fontcolor.set(el.Value.ToString());
                                                }

                                                if (el.Name.ToString() == "link")
                                                {
                                                    R.link = el.Value;
                                                }

                                                if (el.Name.ToString() == "shortcut")
                                                {
                                                    R.shortcut = Int32.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "mark")
                                                {
                                                    R.mark = bool.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "transparent")
                                                {
                                                    R.transparent = bool.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "embeddedimage")
                                                {
                                                    R.embeddedimage = bool.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "imagedata")
                                                {
                                                    R.image = new Bitmap(new MemoryStream(Convert.FromBase64String(el.Value)));
                                                    R.height = R.image.Height;
                                                    R.width = R.image.Width;
                                                    R.isimage = true;
                                                }

                                                if (el.Name.ToString() == "image")
                                                {
                                                    R.imagepath = el.Value.ToString();
                                                    if (Os.FileExists(R.imagepath))
                                                    {
                                                        try
                                                        {
                                                            string ext = "";
                                                            ext = Os.getExtension(R.imagepath).ToLower();

                                                            if (ext == ".jpg" || ext == ".png" || ext == ".ico" || ext == ".bmp") // skratenie cesty k suboru
                                                            {
                                                                R.image = Media.getImage(R.imagepath);
                                                                if (ext != ".ico") R.image.MakeTransparent(Color.White);
                                                                R.height = R.image.Height;
                                                                R.width = R.image.Width;
                                                                R.isimage = true;
                                                            }
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            Program.log.write("load image from xml error: " + ex.Message);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        R.imagepath = "";
                                                    }
                                                }

                                                if (el.Name.ToString() == "timecreate")
                                                {
                                                    R.timecreate = el.Value;
                                                }

                                                if (el.Name.ToString() == "timemodify")
                                                {
                                                    R.timemodify = el.Value;
                                                }

                                                if (el.Name.ToString() == "attachment")
                                                {
                                                    R.attachment = el.Value;
                                                }

                                                if (el.Name.ToString() == "layer")
                                                {
                                                    R.layer = Int32.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "protect")
                                                {
                                                    R.protect = bool.Parse(el.Value);
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                Program.log.write("Data has wrong structure. : error: " + ex.Message);
                                            }
                                        }

                                        NewNodes.Add(R);
                                    }
                                }
                            }

                            if (diagram.Name.ToString() == "lines")
                            {
                                foreach (XElement block in diagram.Descendants())
                                {
                                    if (block.Name.ToString() == "line")
                                    {
                                        Line L = new Line();
                                        foreach (XElement el in block.Descendants())
                                        {
                                            try
                                            {
                                                if (el.Name.ToString() == "start")
                                                {
                                                    L.start = Int32.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "end")
                                                {
                                                    L.end = Int32.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "arrow")
                                                {
                                                    L.arrow = el.Value == "1" ? true : false;
                                                }

                                                if (el.Name.ToString() == "color")
                                                {
                                                    L.color.set(el.Value.ToString());
                                                }

                                                if (el.Name.ToString() == "width")
                                                {
                                                    L.width = Int32.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "layer")
                                                {
                                                    L.layer = Int32.Parse(el.Value);
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                Program.log.write("Data has wrong structure. : error: " + ex.Message);
                                            }
                                        }
                                        NewLines.Add(L);
                                    }

                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Program.log.write("Data has wrong structure. : error: " + ex.Message);
            }

            List<MappedNode> maps = new List<MappedNode>();

            Nodes NewReorderedNodes = new Nodes(); // order nodes parent first (layer must exist when sub node is created)
            this.nodesReorderNodes(0, null, NewNodes, NewReorderedNodes);

            int layerParent = 0;

            MappedNode mappedNode;
            Nodes createdNodes = new Nodes();
            Node newNode = null;
            int oldId = 0;
            foreach (Node rec in NewReorderedNodes)
            {
                layerParent = 0;
                if (rec.layer == 0)
                {
                    layerParent = layer;
                }
                else
                {
                    foreach (MappedNode mapednode in maps)
                    {
                        if (rec.layer == mapednode.oldId)
                        {
                            layerParent = mapednode.newNode.id;
                            break;
                        }
                    }
                }

                rec.layer = layerParent;
                rec.position.add(position);
                rec.resize();

                oldId = rec.id;
                newNode = this.createNode(rec);

                if (newNode != null) {
                    mappedNode = new MappedNode();
                    mappedNode.oldId = oldId;
                    mappedNode.newNode = newNode;
                    createdNodes.Add(newNode);
                    maps.Add(mappedNode);
                }
            }

            // fix layers and shortcuts
            foreach (Node rec in NewNodes)
            {
                if (rec.shortcut != 0)
                {
                    foreach (MappedNode mapednode in maps)
                    {
                        if (rec.shortcut == mapednode.oldId)
                        {
                            rec.shortcut = mapednode.newNode.id;
                            break;
                        }
                    }
                }
            }

            Lines createdLines = new Lines();
            Line newLine = null;
            foreach (Line line in NewLines)
            {
                foreach (MappedNode mapbegin in maps)
                {
                    if (line.start == mapbegin.oldId)
                    {
                        foreach (MappedNode mapend in maps)
                        {
                            if (line.end == mapend.oldId)
                            {
                                newLine = this.Connect(
                                    mapbegin.newNode,
                                    mapend.newNode,
                                    line.arrow,
                                    line.color,
                                    line.width
                                );

                                if (newLine != null)
                                {
                                    createdLines.Add(newLine);
                                }
                            }
                        }
                    }
                }
            }

            return new DiagramBlock(NewNodes, createdLines);
        }
Exemplo n.º 16
0
 public void unsave(string type, Node node, Line line, Position position = null, int layer = 0)
 {
     Nodes nodes = new Nodes();
     nodes.Add(node);
     Lines lines = new Lines();
     lines.Add(line);
     this.unsave(type, nodes, lines, position, layer);
 }
Exemplo n.º 17
0
        /// <summary>
        /// Read and parse the DXF file
        /// </summary>
        public void Read()
        {
            bool entitysection = false;

            CodePair code = this.ReadPair();

            while ((code.Value != "EOF") && (!dxfReader.EndOfStream))
            {
                if (code.Code == 0)
                {
                    //Have we reached the entities section yet?
                    if (!entitysection)
                    {
                        //No, so keep going until we find the ENTIIES section (and since we are here, let's try to read the layers)
                        switch (code.Value)
                        {
                        case "SECTION":
                            string sec = ReadSection(ref code);
                            if (sec == "ENTITIES")
                            {
                                entitysection = true;
                            }
                            break;

                        case "LAYER":
                            Layer layer = ReadLayer(ref code);
                            Layers.Add(layer);
                            break;

                        default:
                            code = this.ReadPair();
                            break;
                        }
                    }
                    else
                    {
                        //Yes, so let's read the entities
                        switch (code.Value)
                        {
                        case "LINE":
                            Line line = ReadLine(ref code);
                            Lines.Add(line);
                            break;

                        case "CIRCLE":
                            Circle circle = ReadCircle(ref code);
                            Circles.Add(circle);
                            break;

                        case "ARC":
                            Arc arc = ReadArc(ref code);
                            Arcs.Add(arc);
                            break;

                        case "POINT":
                            Point point = ReadPoint(ref code);
                            Points.Add(point);
                            break;

                        case "TEXT":
                            Text text = ReadText(ref code);
                            Texts.Add(text);
                            break;

                        case "POLYLINE":
                            Polyline polyline = ReadPolyline(ref code);
                            Polylines.Add(polyline);
                            break;

                        case "LWPOLYLINE":
                            Polyline lwpolyline = ReadLwPolyline(ref code);
                            Polylines.Add(lwpolyline);
                            break;

                        default:
                            code = this.ReadPair();
                            break;
                        }
                    }
                }
                else
                {
                    code = this.ReadPair();
                }
            }
        }
        protected virtual void AddConstructors(int start)
        {
            if (ClassDefinition.Constructors == null || ClassDefinition.Constructors.Count == 0)
            {
                return;
            }

            if (ClassDefinition.UseRegionsToGroupClassMembers)
            {
                Lines.Add(new CodeLine("{0}#region {1}", Indent(start + 1), ConstructorsRegionDescription));
            }

            for (var i = 0; i < ClassDefinition.Constructors.Count; i++)
            {
                var constructor = ClassDefinition.Constructors[i];

                AddDocumentation(start + 1, constructor);

                Lines.Add(new CodeLine("{0}{1} {2}({3})", Indent(start + 1), constructor.AccessModifier.ToString().ToLower(), ObjectDefinition.Name, constructor.Parameters.Count == 0 ? string.Empty : string.Join(", ", constructor.Parameters.Select(item => string.Format("{0} {1}", item.Type, item.Name)))));

                if (!string.IsNullOrEmpty(constructor.Invocation))
                {
                    Lines.Add(new CodeLine("{0}: {1}", Indent(start + 2), constructor.Invocation));
                }

                Lines.Add(new CodeLine("{0}{1}", Indent(start + 1), "{"));

                foreach (var line in constructor.Lines)
                {
                    if (line.IsComment())
                    {
                        Lines.Add(new CommentLine("{0}{1}", Indent(start + 2 + line.Indent), GetComment(line.Content)));
                    }
                    else if (line.IsPreprocessorDirective())
                    {
                        Lines.Add(new PreprocessorDirectiveLine("{0}{1}", Indent(start + 2 + line.Indent), GetPreprocessorDirective(line.Content)));
                    }
                    else if (line.IsReturn())
                    {
                        Lines.Add(new ReturnLine("{0}{1}", Indent(start + 2 + line.Indent), GetReturn(line.Content)));
                    }
                    else if (line.IsTodo())
                    {
                        Lines.Add(new TodoLine("{0}{1}", Indent(start + 2 + line.Indent), GetTodo(line.Content)));
                    }
                    else
                    {
                        Lines.Add(new CodeLine("{0}{1}", Indent(start + 2 + line.Indent), line.Content));
                    }
                }

                Lines.Add(new CodeLine("{0}{1}", Indent(start + 1), "}"));

                if (i < ClassDefinition.Constructors.Count - 1)
                {
                    Lines.Add(new CodeLine());
                }
            }

            Lines.Add(new CodeLine());

            if (ClassDefinition.UseRegionsToGroupClassMembers)
            {
                Lines.Add(new CodeLine());
                Lines.Add(new CodeLine("{0}#endregion", Indent(start + 1)));
                Lines.Add(new CodeLine());
            }
        }
Exemplo n.º 19
0
 public void Comment(string line = "") => Lines.Add(line);
        protected virtual void AddIndexers(int start)
        {
            if (ClassDefinition.Indexers == null || ClassDefinition.Indexers.Count == 0)
            {
                return;
            }

            if (ClassDefinition.UseRegionsToGroupClassMembers)
            {
                Lines.Add(new CodeLine("{0}#region {1}", Indent(start + 1), IndexersRegionDescription));
            }

            for (var i = 0; i < ClassDefinition.Indexers.Count; i++)
            {
                var indexer = ClassDefinition.Indexers[i];

                var parameters = string.Join(", ", indexer.Parameters.Select(item => string.Format("{0} {1}", item.Type, item.Name)));

                Lines.Add(new CodeLine("{0}{1} {2} {3}[{4}]", Indent(start + 1), indexer.AccessModifier.ToString().ToLower(), indexer.Type, "this", parameters));

                Lines.Add(new CodeLine("{0}{1}", Indent(start + 1), "{"));

                if (indexer.GetBody.Count > 0)
                {
                    Lines.Add(new CodeLine("{0}get", Indent(start + 2)));

                    Lines.Add(new CodeLine("{0}{1}", Indent(start + 2), "{"));

                    foreach (var line in indexer.GetBody)
                    {
                        if (line.IsComment())
                        {
                            Lines.Add(new CommentLine("{0}{1}", Indent(start + 3 + line.Indent), GetComment(line.Content)));
                        }
                        else if (line.IsPreprocessorDirective())
                        {
                            Lines.Add(new PreprocessorDirectiveLine("{0}{1}", Indent(start + 3 + line.Indent), GetPreprocessorDirective(line.Content)));
                        }
                        else if (line.IsReturn())
                        {
                            Lines.Add(new ReturnLine("{0}{1}", Indent(start + 3 + line.Indent), GetReturn(line.Content)));
                        }
                        else if (line.IsTodo())
                        {
                            Lines.Add(new TodoLine("{0}{1}", Indent(start + 3 + line.Indent), GetTodo(line.Content)));
                        }
                        else
                        {
                            Lines.Add(new CodeLine("{0}{1}", Indent(start + 3 + line.Indent), line.Content));
                        }
                    }

                    Lines.Add(new CodeLine("{0}{1}", Indent(start + 2), "}"));
                }

                if (indexer.SetBody.Count > 0)
                {
                    Lines.Add(new CodeLine("{0}set", Indent(start + 2)));

                    Lines.Add(new CodeLine("{0}{1}", Indent(start + 2), "{"));

                    foreach (var line in indexer.SetBody)
                    {
                        if (line.IsComment())
                        {
                            Lines.Add(new CommentLine("{0}{1}", Indent(start + 3 + line.Indent), GetComment(line.Content)));
                        }
                        else if (line.IsPreprocessorDirective())
                        {
                            Lines.Add(new PreprocessorDirectiveLine("{0}{1}", Indent(start + 3 + line.Indent), GetPreprocessorDirective(line.Content)));
                        }
                        else if (line.IsReturn())
                        {
                            Lines.Add(new ReturnLine("{0}{1}", Indent(start + 3 + line.Indent), GetReturn(line.Content)));
                        }
                        else if (line.IsTodo())
                        {
                            Lines.Add(new TodoLine("{0}{1}", Indent(start + 3 + line.Indent), GetTodo(line.Content)));
                        }
                        else
                        {
                            Lines.Add(new CodeLine("{0}{1}", Indent(start + 3 + line.Indent), line.Content));
                        }
                    }

                    Lines.Add(new CodeLine("{0}{1}", Indent(start + 2), "}"));
                }

                Lines.Add(new CodeLine("{0}{1}", Indent(start + 1), "}"));

                if (i < ClassDefinition.Indexers.Count - 1)
                {
                    Lines.Add(new CodeLine());
                }
            }

            Lines.Add(new CodeLine());

            if (ClassDefinition.UseRegionsToGroupClassMembers)
            {
                Lines.Add(new CodeLine());
                Lines.Add(new CodeLine("{0}#endregion", Indent(start + 1)));
                Lines.Add(new CodeLine());
            }
        }
Exemplo n.º 21
0
 /// <summary>
 /// Adds a new line to the version file
 /// </summary>
 /// <param name="Line"></param>
 public void AddLine(string Line)
 {
     Lines.Add(Line);
 }
        public override void Translating()
        {
            if (ObjectDefinition.Namespaces.Count > 0)
            {
                foreach (var item in ObjectDefinition.Namespaces)
                {
                    Lines.Add(new CodeLine("using {0};", item));
                }

                Lines.Add(new CodeLine());
            }

            var start = 0;

            if (!string.IsNullOrEmpty(ObjectDefinition.Namespace))
            {
                start = 1;

                Lines.Add(new CodeLine("namespace {0}", ObjectDefinition.Namespace));
                Lines.Add(new CodeLine("{"));
            }

            AddDocumentation(start, ObjectDefinition);

            this.AddAttributes(start);

            var declaration = new List <string>
            {
                ObjectDefinition.AccessModifier.ToString().ToLower()
            };

            if (ClassDefinition.IsStatic)
            {
                declaration.Add("static");
            }

            if (ClassDefinition.IsAbstract)
            {
                declaration.Add("abstract");
            }

            if (ClassDefinition.IsPartial)
            {
                declaration.Add("partial");
            }

            declaration.Add("class");

            if (ClassDefinition.GenericTypes.Count == 0)
            {
                declaration.Add(ObjectDefinition.Name);
            }
            else
            {
                declaration.Add(string.Format("{0}<{1}>", ObjectDefinition.Name, string.Join(", ", ClassDefinition.GenericTypes.Select(item => item.Name))));
            }

            if (ClassDefinition.HasInheritance)
            {
                declaration.Add(":");

                var parents = new List <string>();

                if (!string.IsNullOrEmpty(ClassDefinition.BaseClass))
                {
                    parents.Add(ClassDefinition.BaseClass);
                }

                if (ClassDefinition.Implements.Count > 0)
                {
                    parents.AddRange(ClassDefinition.Implements);
                }

                declaration.Add(string.Join(", ", parents));
            }

            if (ClassDefinition.GenericTypes.Count > 0)
            {
                declaration.Add(string.Join(", ", ClassDefinition.GenericTypes.Where(item => !string.IsNullOrEmpty(item.Constraint)).Select(item => string.Format("where {0}", item.Constraint))));
            }

            Lines.Add(new CodeLine("{0}{1}", Indent(start), string.Join(" ", declaration)));

            Lines.Add(new CodeLine("{0}{{", Indent(start)));

            AddConstants(start);

            AddEvents(start);

            AddFields(start);

            AddStaticConstructor(start);

            AddConstructors(start);

            AddFinalizer(start);

            AddIndexers(start);

            AddProperties(start);

            AddMethods(start);

            Lines.Add(new CodeLine("{0}{1}", Indent(start), "}"));

            if (!string.IsNullOrEmpty(ObjectDefinition.Namespace))
            {
                Lines.Add(new CodeLine("}"));
            }
        }
Exemplo n.º 23
0
        public Lines getAllLinesFromNode(Node node)
        {
            Lines lines = new Lines();

            Layer layer = this.getLayer(node);

            if (layer != null)
            {
                foreach (Line line in layer.lines)
                {
                    if (line.start == node.id || line.end == node.id)
                    {
                        lines.Add(line);
                    }
                }
            }

            return lines;
        }
        protected virtual void AddProperties(int start)
        {
            if (ClassDefinition.Properties == null || ClassDefinition.Properties.Count == 0)
            {
                return;
            }

            if (ClassDefinition.UseRegionsToGroupClassMembers)
            {
                Lines.Add(new CodeLine("{0}#region {1}", Indent(start + 1), PropertiesRegionDescription));
                Lines.Add(new CodeLine());
            }

            for (var i = 0; i < ClassDefinition.Properties.Count; i++)
            {
                var property = ClassDefinition.Properties[i];

                if (property.Attributes.Count > 0)
                {
                    this.AddAttributes(property, start);
                }

                if (property.IsReadOnly)
                {
                    if (property.GetBody.Count == 0)
                    {
                        Lines.Add(new CodeLine("{0}{1} {2} {3} {{ get; }}", Indent(start + 1), property.AccessModifier.ToString().ToLower(), property.Type, property.Name));
                    }
                    else
                    {
                        var propertySignature = new List <string>
                        {
                            property.AccessModifier.ToString().ToLower()
                        };

                        if (property.IsOverride)
                        {
                            propertySignature.Add("override");
                        }
                        else if (property.IsVirtual)
                        {
                            propertySignature.Add("virtual");
                        }

                        propertySignature.Add(property.Type);

                        propertySignature.Add(property.Name);

                        Lines.Add(new CodeLine("{0}{1}", Indent(start + 1), string.Join(" ", propertySignature)));

                        if (property.GetBody.Count == 1)
                        {
                            Lines.Add(new CodeLine("{0}=> {1}", Indent(start + 2), property.GetBody[0].Content.Replace("return ", string.Empty)));
                        }
                        else
                        {
                            Lines.Add(new CodeLine("{0}{1}", Indent(start + 1), "{"));

                            Lines.Add(new CodeLine("{0}get", Indent(start + 2)));

                            Lines.Add(new CodeLine("{0}{1}", Indent(start + 2), "{"));

                            foreach (var line in property.GetBody)
                            {
                                if (line.IsComment())
                                {
                                    Lines.Add(new CommentLine("{0}{1}", Indent(start + 2 + line.Indent), GetComment(line.Content)));
                                }
                                else if (line.IsReturn())
                                {
                                    Lines.Add(new ReturnLine("{0}{1}", Indent(start + 2 + line.Indent), GetReturn(line.Content)));
                                }
                                else if (line.IsTodo())
                                {
                                    Lines.Add(new TodoLine("{0}{1}", Indent(start + 2 + line.Indent), GetTodo(line.Content)));
                                }
                                else
                                {
                                    Lines.Add(new CodeLine("{0}{1}", Indent(start + 2 + line.Indent), line.Content));
                                }
                            }

                            Lines.Add(new CodeLine("{0}{1}", Indent(start + 2), "}"));

                            Lines.Add(new CodeLine("{0}{1}", Indent(start + 1), "}"));
                        }
                    }
                }
                else if (property.IsAutomatic)
                {
                    var propertySignature = new List <string>
                    {
                        property.AccessModifier.ToString().ToLower()
                    };

                    if (property.IsOverride)
                    {
                        propertySignature.Add("override");
                    }
                    else if (property.IsVirtual)
                    {
                        propertySignature.Add("virtual");
                    }

                    propertySignature.Add(property.Type);

                    propertySignature.Add(property.Name);

                    Lines.Add(new CodeLine("{0}{1} {{ get; set; }}", Indent(start + 1), string.Join(" ", propertySignature)));
                }
                else
                {
                    Lines.Add(new CodeLine("{0}{1} {2} {3}", Indent(start + 1), property.AccessModifier.ToString().ToLower(), property.Type, property.Name));

                    Lines.Add(new CodeLine("{0}{1}", Indent(start + 1), "{"));

                    Lines.Add(new CodeLine("{0}get", Indent(start + 2)));

                    Lines.Add(new CodeLine("{0}{1}", Indent(start + 2), "{"));

                    foreach (var line in property.GetBody)
                    {
                        if (line.IsComment())
                        {
                            Lines.Add(new CommentLine("{0}{1}", Indent(start + 3 + line.Indent), GetComment(line.Content)));
                        }
                        else if (line.IsPreprocessorDirective())
                        {
                            Lines.Add(new PreprocessorDirectiveLine("{0}{1}", Indent(start + 3 + line.Indent), GetPreprocessorDirective(line.Content)));
                        }
                        else if (line.IsReturn())
                        {
                            Lines.Add(new ReturnLine("{0}{1}", Indent(start + 3 + line.Indent), GetReturn(line.Content)));
                        }
                        else if (line.IsTodo())
                        {
                            Lines.Add(new TodoLine("{0}{1}", Indent(start + 3 + line.Indent), GetTodo(line.Content)));
                        }
                        else
                        {
                            Lines.Add(new CodeLine("{0}{1}", Indent(start + 3 + line.Indent), line.Content));
                        }
                    }

                    Lines.Add(new CodeLine("{0}{1}", Indent(start + 2), "}"));

                    Lines.Add(new CodeLine("{0}set", Indent(start + 2)));

                    Lines.Add(new CodeLine("{0}{1}", Indent(start + 2), "{"));

                    foreach (var line in property.SetBody)
                    {
                        if (line.IsComment())
                        {
                            Lines.Add(new CommentLine("{0}{1}", Indent(start + 3 + line.Indent), GetComment(line.Content)));
                        }
                        else if (line.IsPreprocessorDirective())
                        {
                            Lines.Add(new PreprocessorDirectiveLine("{0}{1}", Indent(start + 3 + line.Indent), GetPreprocessorDirective(line.Content)));
                        }
                        else if (line.IsReturn())
                        {
                            Lines.Add(new ReturnLine("{0}{1}", Indent(start + 3 + line.Indent), GetReturn(line.Content)));
                        }
                        else if (line.IsTodo())
                        {
                            Lines.Add(new TodoLine("{0}{1}", Indent(start + 3 + line.Indent), GetTodo(line.Content)));
                        }
                        else
                        {
                            Lines.Add(new CodeLine("{0}{1}", Indent(start + 3 + line.Indent), line.Content));
                        }
                    }

                    Lines.Add(new CodeLine("{0}{1}", Indent(start + 2), "}"));

                    Lines.Add(new CodeLine("{0}{1}", Indent(start + 1), "}"));
                }

                if (i < ClassDefinition.Properties.Count - 1)
                {
                    Lines.Add(new CodeLine());
                }
            }

            Lines.Add(new CodeLine());

            if (ClassDefinition.UseRegionsToGroupClassMembers)
            {
                Lines.Add(new CodeLine("{0}#endregion", Indent(start + 1)));
                Lines.Add(new CodeLine());
                Lines.Add(new CodeLine());
            }
        }
Exemplo n.º 25
0
 public void unsave(string type, Line line, Position position = null, int layer = 0)
 {
     Lines lines = new Lines();
     lines.Add(line);
     this.unsave(type, null, lines, position, layer);
 }
        protected virtual void AddMethods(int start)
        {
            if (ClassDefinition.Methods == null || ClassDefinition.Methods.Count == 0)
            {
                return;
            }

            if (ClassDefinition.UseRegionsToGroupClassMembers)
            {
                Lines.Add(new CodeLine("{0}#region {1}", Indent(start + 2), MethodsRegionDescription));
                Lines.Add(new CodeLine());
            }

            for (var i = 0; i < ClassDefinition.Methods.Count; i++)
            {
                var method = ClassDefinition.Methods[i];

                this.AddAttributes(method, start);

                var methodSignature = new List <string>
                {
                    method.AccessModifier.ToString().ToLower()
                };

                if (method.IsStatic)
                {
                    methodSignature.Add("static");
                }
                else if (method.IsOverride)
                {
                    methodSignature.Add("override");
                }
                else if (method.IsVirtual)
                {
                    methodSignature.Add("virtual");
                }
                else if (method.IsAbstract)
                {
                    methodSignature.Add("abstract");
                }

                if (method.IsAsync)
                {
                    methodSignature.Add("async");
                }

                methodSignature.Add(string.IsNullOrEmpty(method.Type) ? "void" : method.Type);

                var parameters = new List <string>();

                for (var j = 0; j < method.Parameters.Count; j++)
                {
                    var parameter = method.Parameters[j];

                    var parametersAttributes = this.AddAttributes(parameter);

                    var parameterDef = string.Empty;

                    if (string.IsNullOrEmpty(parameter.DefaultValue))
                    {
                        if (string.IsNullOrEmpty(parametersAttributes))
                        {
                            parameterDef = string.Format("{0} {1}", parameter.Type, parameter.Name);
                        }
                        else
                        {
                            parameterDef = string.Format("{0}{1} {2}", parametersAttributes, parameter.Type, parameter.Name);
                        }
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(parametersAttributes))
                        {
                            parameterDef = string.Format("{0} {1} = {2}", parameter.Type, parameter.Name, parameter.DefaultValue);
                        }
                        else
                        {
                            parameterDef = string.Format("{0}{1} {2} = {3}", parametersAttributes, parameter.Type, parameter.Name, parameter.DefaultValue);
                        }
                    }

                    parameters.Add(method.IsExtension && j == 0 ? string.Format("this {0}", parameterDef) : parameterDef);
                }

                if (method.GenericTypes.Count == 0)
                {
                    methodSignature.Add(string.Format("{0}({1})", method.Name, string.Join(", ", parameters)));
                }
                else
                {
                    methodSignature.Add(string.Format("{0}<{1}>({2})", method.Name, string.Join(", ", method.GenericTypes.Select(item => item.Name)), string.Join(", ", parameters)));
                }

                if (method.GenericTypes.Count > 0)
                {
                    methodSignature.Add(string.Join(", ", method.GenericTypes.Where(item => !string.IsNullOrEmpty(item.Constraint)).Select(item => string.Format("where {0}", item.Constraint))));
                }

                Lines.Add(new CodeLine("{0}{1}", Indent(start + 1), string.Join(" ", methodSignature)));

                if (method.Lines.Count == 0)
                {
                    Lines.Add(new CodeLine("{0}{1}", Indent(start + 1), "{"));
                    Lines.Add(new CodeLine("{0}{1}", Indent(start + 1), "}"));
                }
                else if (method.Lines.Count == 1)
                {
                    var line = method.Lines[0];

                    if (line.IsReturn())
                    {
                        var content = line.Content.StartsWith("return ") ? line.Content.Insert(0, "=> ") : line.Content.Insert(0, "=> ");

                        Lines.Add(new ReturnLine("{0}{1}", Indent(start + 2), content));
                    }
                    else
                    {
                        Lines.Add(new CodeLine("{0}{1}", Indent(start + 1), "{"));

                        if (line.IsComment())
                        {
                            Lines.Add(new CommentLine("{0}{1}", Indent(start + 2 + line.Indent), GetComment(line.Content)));
                        }
                        else if (line.IsPreprocessorDirective())
                        {
                            Lines.Add(new PreprocessorDirectiveLine("{0}{1}", Indent(start + 2 + line.Indent), GetPreprocessorDirective(line.Content)));
                        }
                        else if (line.IsReturn())
                        {
                            Lines.Add(new ReturnLine("{0}{1}", Indent(start + 2 + line.Indent), GetReturn(line.Content)));
                        }
                        else if (line.IsTodo())
                        {
                            Lines.Add(new TodoLine("{0}{1}", Indent(start + 2 + line.Indent), GetTodo(line.Content)));
                        }
                        else
                        {
                            Lines.Add(new CodeLine("{0}{1}", Indent(start + 2 + line.Indent), line.Content));
                        }

                        Lines.Add(new CodeLine("{0}{1}", Indent(start + 1), "}"));
                    }
                }
                else if (method.Lines.Count > 1)
                {
                    Lines.Add(new CodeLine("{0}{1}", Indent(start + 1), "{"));

                    foreach (var line in method.Lines)
                    {
                        if (line.IsComment())
                        {
                            Lines.Add(new CommentLine("{0}{1}", Indent(start + 2 + line.Indent), GetComment(line.Content)));
                        }
                        else if (line.IsPreprocessorDirective())
                        {
                            Lines.Add(new PreprocessorDirectiveLine("{0}{1}", Indent(start + 2 + line.Indent), GetPreprocessorDirective(line.Content)));
                        }
                        else if (line.IsReturn())
                        {
                            Lines.Add(new ReturnLine("{0}{1}", Indent(start + 2 + line.Indent), GetReturn(line.Content)));
                        }
                        else if (line.IsTodo())
                        {
                            Lines.Add(new TodoLine("{0}{1}", Indent(start + 2 + line.Indent), GetTodo(line.Content)));
                        }
                        else
                        {
                            Lines.Add(new CodeLine("{0}{1}", Indent(start + 2 + line.Indent), line.Content));
                        }
                    }

                    Lines.Add(new CodeLine("{0}{1}", Indent(start + 1), "}"));
                }

                if (i < ClassDefinition.Methods.Count - 1)
                {
                    Lines.Add(new CodeLine());
                }
            }

            if (ClassDefinition.UseRegionsToGroupClassMembers)
            {
                Lines.Add(new CodeLine());
                Lines.Add(new CodeLine("{0}#endregion", Indent(start + 2)));
                Lines.Add(new CodeLine());
            }
        }
Exemplo n.º 27
0
 public void AddNode(SyntaxNode node) => Lines.Add(node.WithLeadingEndOfLineTrivia().ToFullStringWithoutPragmaWarningDirectiveTrivia());
Exemplo n.º 28
0
        private Dictionary <int, Connection> SetLines(Dictionary <int, Connection> connections)
        {
            var gridCopy            = Grid.Clone() as int[, ];
            var thirdIterationLines = new List <LineModel>();
            var redoLast            = new Dictionary <int, Connection>();

            foreach (var connectionWithId in connections)
            {
                int x1 = 0, x2 = 0, y1 = 0, y2 = 0;

                for (int i = 0; i < gridCopy.GetLength(0); i++)
                {
                    for (int j = 0; j < gridCopy.GetLength(1); j++)
                    {
                        if (gridCopy[i, j] == connectionWithId.Value.GetFirstNodeId())
                        {
                            gridCopy[i, j] = 1;
                            x1             = i;
                            y1             = j;
                        }
                        else if (gridCopy[i, j] == connectionWithId.Value.GetSecondNodeId())
                        {
                            gridCopy[i, j] = 2;
                            x2             = i;
                            y2             = j;
                        }
                        else if (gridCopy[i, j] > 0)
                        {
                            gridCopy[i, j] = int.MaxValue;
                        }
                    }
                }

                LineModel newLine = null;
                int[][]   moves1  = null;
                int[][]   moves2  = null;

                if (x1 > x2 && y1 >= y2)
                {
                    moves1 = MovesProvider.UpLeft;
                    moves2 = MovesProvider.LeftUp;
                }
                else if (x1 > x2 && y1 < y2)
                {
                    moves1 = MovesProvider.UpRight;
                    moves2 = MovesProvider.RightUp;
                }
                else if (x1 <= x2 && y1 >= y2)
                {
                    moves1 = MovesProvider.DownLeft;
                    moves2 = MovesProvider.LeftDown;
                }
                else if (x1 <= x2 && y1 < y2)
                {
                    moves1 = MovesProvider.DownRight;
                    moves2 = MovesProvider.RightDown;
                }

                var optTurns = Math.Abs(x1 - x2) == 0 || Math.Abs(y1 - y2) == 0 ? 0 : 1;

                newLine = new LeeAlgorithmInterpreter().DoYourJob(gridCopy, moves1, moves2, gridCopy.GetLength(0) + gridCopy.GetLength(1), optTurns, connectionWithId.Key, x1, y1, x2, y2);
                if (newLine.GetPointsOfLine().Count != 0)
                {
                    Lines.Add(newLine);
                    if (!newLine.IsReversed)
                    {
                        newLine.AddPointAtStartOfLine(x1, y1);
                    }
                    else
                    {
                        newLine.AddPointAtEndOfLine(x2, y2);
                    }
                }
                else
                {
                    redoLast.Add(connectionWithId.Key, connectionWithId.Value);
                }

                thirdIterationLines.Add(newLine);
                gridCopy = Grid.Clone() as int[, ];
                foreach (var line in thirdIterationLines)
                {
                    for (int i = 1; i < line.GetPointsOfLine().Count - 1; i++)
                    {
                        gridCopy[line.GetPointsOfLine()[i].x, line.GetPointsOfLine()[i].y] = int.MaxValue;
                    }
                }
            }
            return(redoLast);
        }
Exemplo n.º 29
0
    public void Update()
    {
        Hierarchy.Push(Matrix.T(0, 0, -0.3f));

        UI.WindowBegin("Alignment", ref alignWindow, new Vec2(20, 0) * U.cm);
        Vec2 size = new Vec2(5 * U.cm, UI.LineHeight);

        if (UI.Radio("Left", alignX == TextAlign.XLeft, size))
        {
            alignX = TextAlign.XLeft;
        }
        UI.SameLine();
        if (UI.Radio("CenterX", alignX == TextAlign.XCenter, size))
        {
            alignX = TextAlign.XCenter;
        }
        UI.SameLine();
        if (UI.Radio("Right", alignX == TextAlign.XRight, size))
        {
            alignX = TextAlign.XRight;
        }
        if (UI.Radio("Top", alignY == TextAlign.YTop, size))
        {
            alignY = TextAlign.YTop;
        }
        UI.SameLine();
        if (UI.Radio("CenterY", alignY == TextAlign.YCenter, size))
        {
            alignY = TextAlign.YCenter;
        }
        UI.SameLine();
        if (UI.Radio("Bottom", alignY == TextAlign.YBottom, size))
        {
            alignY = TextAlign.YBottom;
        }
        UI.WindowEnd();

        Hierarchy.Push(Matrix.T(0.1f, 0, 0));
        Text.Add("X Center", Matrix.TR(new Vec3(0, .1f, 0), Quat.LookDir(0, 0, 1)), TextAlign.XCenter | TextAlign.YCenter, alignX | alignY);
        Text.Add("X Left", Matrix.TR(new Vec3(0, .15f, 0), Quat.LookDir(0, 0, 1)), TextAlign.XLeft | TextAlign.YCenter, alignX | alignY);
        Text.Add("X Right", Matrix.TR(new Vec3(0, .2f, 0), Quat.LookDir(0, 0, 1)), TextAlign.XRight | TextAlign.YCenter, alignX | alignY);
        Lines.Add(new Vec3(0, .05f, 0), new Vec3(0, .25f, 0), Color32.White, 0.001f);
        Hierarchy.Pop();

        Hierarchy.Push(Matrix.T(-0.1f, 0, 0));
        Text.Add("Y Center", Matrix.TR(new Vec3(0, .1f, 0), Quat.LookDir(0, 0, 1)), TextAlign.YCenter | TextAlign.XCenter, alignX | alignY);
        Lines.Add(new Vec3(-0.05f, .1f, 0), new Vec3(.05f, .1f, 0), Color32.White, 0.001f);

        Text.Add("Y Top", Matrix.TR(new Vec3(0, .15f, 0), Quat.LookDir(0, 0, 1)), TextAlign.YTop | TextAlign.XCenter, alignX | alignY);
        Lines.Add(new Vec3(-0.05f, .15f, 0), new Vec3(.05f, .15f, 0), Color32.White, 0.001f);

        Text.Add("Y Bottom", Matrix.TR(new Vec3(0, .2f, 0), Quat.LookDir(0, 0, 1)), TextAlign.YBottom | TextAlign.XCenter, alignX | alignY);
        Lines.Add(new Vec3(-0.05f, .2f, 0), new Vec3(.05f, .2f, 0), Color32.White, 0.001f);
        Hierarchy.Pop();

        Hierarchy.Push(Matrix.T(0, -0.1f, 0));
        if (Tests.IsTesting)
        {
            Renderer.Screenshot(Hierarchy.ToWorld(new Vec3(0, 0, 0.09f)), Hierarchy.ToWorld(Vec3.Zero), 600, 300, "../../../docs/img/screenshots/BasicText.jpg");
        }
        /// :CodeSample: Text.MakeStyle Font.FromFile Text.Add
        /// Then it's pretty trivial to just draw some text on the screen! Just call
        /// Text.Add on update. If you don't have a TextStyle available, calling it
        /// without one will just fall back on the default style.
        // Text with an explicit text style
        Text.Add(
            "Here's\nSome\nMulti-line\nText!!",
            Matrix.TR(new Vec3(0.1f, 0, 0), Quat.LookDir(0, 0, 1)),
            style);
        // Text using the default text style
        Text.Add(
            "Here's\nSome\nMulti-line\nText!!",
            Matrix.TR(new Vec3(-0.1f, 0, 0), Quat.LookDir(0, 0, 1)));
        /// :End:

        Hierarchy.Push(Matrix.T(0, -0.2f, 0));
        Text.Add(
            "Here's Some Multi-line Text!!",
            Matrix.TR(new Vec3(0, 0.0f, 0), Quat.LookDir(0, 0, 1)),
            new Vec2(SKMath.Cos(Time.Totalf) * 10 + 11, 20) * U.cm,
            TextFit.Clip,
            style, TextAlign.Center, alignX | alignY);
        Hierarchy.Pop();

        Hierarchy.Pop();

        Hierarchy.Pop();
    }
Exemplo n.º 30
0
        private void SetLinesWithoutObstacles(Dictionary <int, Connection> connections)
        {
            var gridCopy = Grid.Clone() as int[, ];

            foreach (var connectionWithId in connections)
            {
                int x1 = 0, x2 = 0, y1 = 0, y2 = 0;

                for (int i = 0; i < gridCopy.GetLength(0); i++)
                {
                    for (int j = 0; j < gridCopy.GetLength(1); j++)
                    {
                        if (gridCopy[i, j] == connectionWithId.Value.GetFirstNodeId())
                        {
                            gridCopy[i, j] = 1;
                            x1             = i;
                            y1             = j;
                        }
                        else if (gridCopy[i, j] == connectionWithId.Value.GetSecondNodeId())
                        {
                            gridCopy[i, j] = 2;
                            x2             = i;
                            y2             = j;
                        }
                        else if (gridCopy[i, j] > 0)
                        {
                            gridCopy[i, j] = int.MaxValue;
                        }
                    }
                }

                LineModel newLine = null;
                int[][]   moves1  = null;
                int[][]   moves2  = null;

                if (x1 > x2 && y1 >= y2)
                {
                    moves1 = MovesProvider.UpLeft;
                    moves2 = MovesProvider.LeftUp;
                }
                else if (x1 > x2 && y1 < y2)
                {
                    moves1 = MovesProvider.UpRight;
                    moves2 = MovesProvider.RightUp;
                }
                else if (x1 <= x2 && y1 >= y2)
                {
                    moves1 = MovesProvider.DownLeft;
                    moves2 = MovesProvider.LeftDown;
                }
                else if (x1 <= x2 && y1 < y2)
                {
                    moves1 = MovesProvider.DownRight;
                    moves2 = MovesProvider.RightDown;
                }

                var optTurns = Math.Abs(x1 - x2) == 0 || Math.Abs(y1 - y2) == 0 ? 0 : 1;

                newLine = new LeeAlgorithmInterpreter().DoYourJob(gridCopy, moves1, moves2, (Math.Abs(x1 - x2) + Math.Abs(y1 - y2)) + 4, optTurns, connectionWithId.Key, x1, y1, x2, y2);
                if (newLine.GetPointsOfLine().Count != 0)
                {
                    Lines.Add(newLine);
                    if (!newLine.IsReversed)
                    {
                        newLine.AddPointAtStartOfLine(x1, y1);
                    }
                    else
                    {
                        newLine.AddPointAtEndOfLine(x2, y2);
                    }
                }
            }
        }
Exemplo n.º 31
0
        private void GenerateLines()
        {
            string line = "        public " + Structure.Type + " " + Structure.Name + " { get; set; }";

            Lines.Add(line);
        }
Exemplo n.º 32
0
        private Dictionary <int, Connection> SetLines(List <Connection> connections)
        {
            var gridCopy = Grid.Clone() as int[, ];
            int id       = 1;

            var  redo = new Dictionary <int, Connection>();
            bool cont = true;

            connections.Reverse();
            var shuffled = connections.OrderBy(x => new Random().Next()).ToList();

            foreach (var connection in /*shuffled*/ connections)
            {
                //var gridCopy = Grid.Clone() as int[,];
                int x1 = 0, x2 = 0, y1 = 0, y2 = 0;

                for (int i = 0; i < gridCopy.GetLength(0); i++)
                {
                    for (int j = 0; j < gridCopy.GetLength(1); j++)
                    {
                        if (gridCopy[i, j] == connection.GetFirstNodeId())
                        {
                            if (j > 0 && i > 0 && j < gridCopy.GetLength(1) - 1 && i < gridCopy.GetLength(0) - 1 && gridCopy[i, j - 1] == int.MaxValue && gridCopy[i, j + 1] == int.MaxValue && gridCopy[i - 1, j] == int.MaxValue && gridCopy[i + 1, j] == int.MaxValue)
                            {
                                if (!redo.ContainsKey(id))
                                {
                                    redo.Add(id, connection);
                                }
                                cont = false;
                            }
                            gridCopy[i, j] = 1;
                            x1             = i;
                            y1             = j;
                        }
                        else if (gridCopy[i, j] == connection.GetSecondNodeId())
                        {
                            if (j > 0 && i > 0 && j < gridCopy.GetLength(1) - 1 && i < gridCopy.GetLength(0) - 1 && gridCopy[i, j - 1] == int.MaxValue && gridCopy[i, j + 1] == int.MaxValue && gridCopy[i - 1, j] == int.MaxValue && gridCopy[i + 1, j] == int.MaxValue)
                            {
                                if (!redo.ContainsKey(id))
                                {
                                    redo.Add(id, connection);
                                }
                                cont = false;
                            }
                            gridCopy[i, j] = 2;
                            x2             = i;
                            y2             = j;
                        }
                        else if (gridCopy[i, j] > 0)
                        {
                            gridCopy[i, j] = int.MaxValue;
                        }
                    }
                }

                if ((x2 == 0 && y2 == 0) || (x1 == 0 && y1 == 0))
                {
                    id++;
                    gridCopy = Grid.Clone() as int[, ];
                    continue;
                }

                if (cont)
                {
                    LineModel newLine = null;
                    int[][]   moves1  = null;
                    int[][]   moves2  = null;

                    if (x1 > x2 && y1 >= y2)
                    {
                        moves1 = MovesProvider.UpLeft;
                        moves2 = MovesProvider.LeftUp;
                    }
                    else if (x1 > x2 && y1 < y2)
                    {
                        moves1 = MovesProvider.UpRight;
                        moves2 = MovesProvider.RightUp;
                    }
                    else if (x1 <= x2 && y1 >= y2)
                    {
                        moves1 = MovesProvider.DownLeft;
                        moves2 = MovesProvider.LeftDown;
                    }
                    else if (x1 <= x2 && y1 < y2)
                    {
                        moves1 = MovesProvider.DownRight;
                        moves2 = MovesProvider.RightDown;
                    }

                    var optTurns = Math.Abs(x1 - x2) == 0 || Math.Abs(y1 - y2) == 0 ? 0 : 1;

                    newLine = new LeeAlgorithmInterpreter().DoYourJob(gridCopy, moves1, moves2, /*(Math.Abs(x1 - x2) + Math.Abs(y1 - y2)) + 4*/
                                                                      Grid.GetLength(1) + Grid.GetLength(0), optTurns, id, x1, y1, x2, y2);
                    if (newLine.GetPointsOfLine().Count != 0)
                    {
                        Lines.Add(newLine);
                        if (!newLine.IsReversed)
                        {
                            newLine.AddPointAtStartOfLine(x1, y1);
                        }
                        else
                        {
                            newLine.AddPointAtEndOfLine(x2, y2);
                        }
                    }
                    else
                    {
                        redo.Add(id, connection);
                    }
                }
                else
                {
                    cont = true;
                }
                id++;
                gridCopy = Grid.Clone() as int[, ];
                foreach (var line in Lines)
                {
                    for (int i = 1; i < line.GetPointsOfLine().Count - 1; i++)
                    {
                        gridCopy[line.GetPointsOfLine()[i].x, line.GetPointsOfLine()[i].y] = int.MaxValue;
                    }
                }
            }
            return(redo);
        }
Exemplo n.º 33
0
        public override void Translating()
        {
            var output = new StringBuilder();

            if (EnumDefinition.Namespaces.Count > 0)
            {
                foreach (var item in EnumDefinition.Namespaces)
                {
                    Lines.Add(new CodeLine("using {0};", item));
                }

                Lines.Add(new CodeLine());
            }

            var start = 0;

            if (!string.IsNullOrEmpty(EnumDefinition.Namespace))
            {
                start = 1;

                Lines.Add(new CodeLine("namespace {0}", EnumDefinition.Namespace));

                Lines.Add(new CodeLine("{0}", "{"));
            }

            AddDocumentation(start, EnumDefinition);

            this.AddAttributes(start);

            var declaration = new List <string>
            {
                EnumDefinition.AccessModifier.ToString().ToLower()
            };

            declaration.Add("enum");

            declaration.Add(EnumDefinition.Name);

            if (!string.IsNullOrEmpty(EnumDefinition.BaseType))
            {
                declaration.Add(":");
                declaration.Add(EnumDefinition.BaseType);
            }

            Lines.Add(new CodeLine("{0}{1}", Indent(start), string.Join(" ", declaration)));

            Lines.Add(new CodeLine("{0}{1}", Indent(start), "{"));

            for (var i = 0; i < EnumDefinition.Sets.Count; i++)
            {
                var set = EnumDefinition.Sets[i];

                // todo: Add attributes for options

                Lines.Add(new CodeLine("{0}{1}", Indent(start + 1), string.Format("{0} = {1}{2}", set.Name, set.Value, i < EnumDefinition.Sets.Count - 1 ? "," : "")));
            }

            Lines.Add(new CodeLine("{0}{1}", Indent(start), "}"));

            if (!string.IsNullOrEmpty(EnumDefinition.Namespace))
            {
                Lines.Add(new CodeLine("}"));
            }
        }
Exemplo n.º 34
0
 public void AddLine()
 {
     Lines.Add(new CartEditorLineModel());
 }
Exemplo n.º 35
0
 /// <summary>
 ///   <para>Creates new result instance.</para>
 /// </summary>
 /// <param name="code">HTTP result status code.</param>
 /// <param name="language">Languages pair, representing text's translation direction.</param>
 /// <param name="text">Translated version of text.</param>
 /// <exception cref="ArgumentNullException">If either <paramref name="language"/> or <paramref name="text"/> is a <c>null</c> reference.</exception>
 /// <exception cref="ArgumentException">If either <paramref name="language"/> or <paramref name="text"/> is <see cref="string.Empty"/> string.</exception>
 public TranslationResult(int code, string language, string text) : this()
 {
     Code     = code;
     Language = language;
     Lines.Add(text);
 }
Exemplo n.º 36
0
        public void TestReport()
        {
            CoverageResult result = new CoverageResult();

            result.Identifier = Guid.NewGuid().ToString();

            Lines lines = new Lines();

            lines.Add(1, 1);
            lines.Add(2, 0);

            Branches branches = new Branches();

            branches.Add(new BranchInfo {
                Line = 1, Hits = 1, Offset = 23, EndOffset = 24, Path = 0, Ordinal = 1
            });
            branches.Add(new BranchInfo {
                Line = 1, Hits = 0, Offset = 23, EndOffset = 27, Path = 1, Ordinal = 2
            });

            Methods methods      = new Methods();
            var     methodString = "System.Void Coverlet.Core.Reporters.Tests.CoberturaReporterTests::TestReport()";

            methods.Add(methodString, new Method());
            methods[methodString].Lines    = lines;
            methods[methodString].Branches = branches;

            Classes classes = new Classes();

            classes.Add("Coverlet.Core.Reporters.Tests.CoberturaReporterTests", methods);

            Documents documents = new Documents();

            documents.Add("doc.cs", classes);

            result.Modules = new Modules();
            result.Modules.Add("module", documents);

            CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;

            Thread.CurrentThread.CurrentCulture = new CultureInfo("it-IT");
            try
            {
                // Assert conversion behaviour to be sure to be in a Italian culture context
                // where decimal char is comma.
                Assert.Equal("1,5", (1.5).ToString());

                CoberturaReporter reporter = new CoberturaReporter();
                string            report   = reporter.Report(result);

                Assert.NotEmpty(report);

                var doc = XDocument.Load(new MemoryStream(Encoding.UTF8.GetBytes(report)));
                Assert.All(doc.Descendants().Attributes().Where(attr => attr.Name.LocalName.EndsWith("-rate")).Select(attr => attr.Value),
                           value =>
                {
                    Assert.DoesNotContain(",", value);
                    Assert.Contains(".", value);
                    Assert.Equal(0.5, double.Parse(value, CultureInfo.InvariantCulture));
                });
            }
            finally
            {
                Thread.CurrentThread.CurrentCulture = currentCulture;
            }
        }
Exemplo n.º 37
0
        public void AddAfter(int line)
        {
            SpCondSENewLineTypeSelector sel = new SpCondSENewLineTypeSelector();
            DialogResult dr = sel.ShowDialog(Editor);

            if (dr != DialogResult.OK)
            {
                return;
            }
            string code = "";

            SpectrCondition.CondTypes type = SpectrCondition.CondTypes.Comment;
            switch (sel.LineType)
            {
            case 0:
                code = "#";
                break;

            case 1:
                code = "p: 1 On()";
                type = SpectrCondition.CondTypes.Prespark;
                break;

            case 2:
                if (Cond.Lines[line].Type == SpectrCondition.CondTypes.Exposition)
                {
                    code = Cond.Lines[line].SourceCode;
                    int on_index  = code.ToLower().IndexOf("on");
                    int off_index = code.ToLower().IndexOf("off");
                    if (off_index > 0)
                    {
                        code = code.Substring(0, off_index) + "on()";
                    }
                }
                else
                {
                    code = "e: 1 (";
                    int[] ss = Common.Dev.Reg.GetSensorSizes();
                    for (int i = 0; i < ss.Length; i++)
                    {
                        code += "0.1";
                        if (i < ss.Length - 1)
                        {
                            code += ";";
                        }
                    }
                    code += ") On()";
                }
                type = SpectrCondition.CondTypes.Exposition;
                break;

            case 3:
                if (Cond.Lines[line].Type == SpectrCondition.CondTypes.Exposition)
                {
                    code = Cond.Lines[line].SourceCode;
                    int on_index  = code.ToLower().IndexOf("on");
                    int off_index = code.ToLower().IndexOf("off");
                    if (on_index > 0)
                    {
                        code = code.Substring(0, on_index) + "off()";
                    }
                }
                else
                {
                    code = "e: 1 (";
                    int[] ss = Common.Dev.Reg.GetSensorSizes();
                    for (int i = 0; i < ss.Length; i++)
                    {
                        code += "0.1";
                        if (i < ss.Length - 1)
                        {
                            code += ";";
                        }
                    }
                    code += ") Off()";
                }
                type = SpectrCondition.CondTypes.Exposition;
                break;

            case 4:
                code = "f:Off";
                type = SpectrCondition.CondTypes.FillLight;
                break;
            }
            line++;
            bool fl = false;
            SpectrConditionCompiledLine cond =
                new SpectrConditionCompiledLine(type, code, line, 0, ref fl);

            if (line < Lines.Count)
            {
                Lines.Insert(line, new SpCondLineEditor(cond, this, line));
            }
            else
            {
                Lines.Add(new SpCondLineEditor(cond, this, line));
            }
            Save();
            ReInitList();
        }
Exemplo n.º 38
0
 /// <summary>
 /// Stop the draw
 /// </summary>
 public void StopDrawing()
 {
     IsDrawing = false;
     Lines.Add(CurrentLine);
     CurrentLine = null;
 }
        protected virtual void AddMethods(int start)
        {
            if (InterfaceDefinition.Methods == null || InterfaceDefinition.Methods.Count == 0)
            {
                return;
            }

            if (InterfaceDefinition.UseRegionsToGroupClassMembers)
            {
                Lines.Add(new CodeLine("{0}#region {1}", Indent(2), MethodsRegionDescription));
                Lines.Add(new CodeLine());
            }

            if (InterfaceDefinition.Properties != null && InterfaceDefinition.Properties.Count > 0)
            {
                Lines.Add(new CodeLine());
            }

            for (var i = 0; i < InterfaceDefinition.Methods.Count; i++)
            {
                var method = InterfaceDefinition.Methods[i];

                AddDocumentation(start + 1, method);

                this.AddAttributes(method, start);

                var methodSignature = new List <string>
                {
                    string.IsNullOrEmpty(method.Type) ? "void" : method.Type
                };

                var parameters = new List <string>();

                for (var j = 0; j < method.Parameters.Count; j++)
                {
                    var parameter = method.Parameters[j];

                    var parametersAttributes = this.AddAttributes(parameter);

                    var parameterDef = string.Empty;

                    if (string.IsNullOrEmpty(parameter.DefaultValue))
                    {
                        if (string.IsNullOrEmpty(parametersAttributes))
                        {
                            parameterDef = string.Format("{0} {1}", parameter.Type, parameter.Name);
                        }
                        else
                        {
                            parameterDef = string.Format("{0}{1} {2}", parametersAttributes, parameter.Type, parameter.Name);
                        }
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(parametersAttributes))
                        {
                            parameterDef = string.Format("{0} {1} = {2}", parameter.Type, parameter.Name, parameter.DefaultValue);
                        }
                        else
                        {
                            parameterDef = string.Format("{0}{1} {2} = {3}", parametersAttributes, parameter.Type, parameter.Name, parameter.DefaultValue);
                        }
                    }

                    parameters.Add(method.IsExtension && j == 0 ? string.Format("this {0}", parameterDef) : parameterDef);
                }

                if (method.GenericTypes.Count == 0)
                {
                    methodSignature.Add(string.Format("{0}({1})", method.Name, string.Join(", ", parameters)));
                }
                else
                {
                    methodSignature.Add(string.Format("{0}<{1}>({2})", method.Name, string.Join(", ", method.GenericTypes.Select(item => item.Name)), string.Join(", ", parameters)));
                }

                if (method.GenericTypes.Count > 0)
                {
                    methodSignature.Add(string.Join(", ", method.GenericTypes.Where(item => !string.IsNullOrEmpty(item.Constraint)).Select(item => string.Format("where {0}", item.Constraint))));
                }

                Lines.Add(new CodeLine("{0}{1};", Indent(start + 1), string.Join(" ", methodSignature)));

                if (i < InterfaceDefinition.Methods.Count - 1)
                {
                    Lines.Add(new CodeLine());
                }
            }

            if (InterfaceDefinition.UseRegionsToGroupClassMembers)
            {
                Lines.Add(new CodeLine("{0}#endregion", Indent(2)));
                Lines.Add(new CodeLine());
            }
        }
Exemplo n.º 40
0
    public void Update()
    {
        Color colIntersect = Color.HSV(0, 0.8f, 1);
        Color colTest      = Color.HSV(0, 0.6f, 1);
        Color colObj       = Color.HSV(0.05f, 0.7f, 1);
        Color active       = new Color(1, 1, 1, 0.7f);
        Color notActive    = new Color(1, 1, 1, 1);

        // Plane and Ray
        bool planeRayActive = UI.AffordanceBegin("PlaneRay", ref posePlaneRay, new Bounds(Vec3.One * 0.4f));

        boundsMesh.Draw(boundsMat, Matrix.TS(Vec3.Zero, 0.4f), planeRayActive ? active:notActive);

        Plane ground    = new Plane(Vec3.Zero, new Vec3(1, 2, 0));
        Ray   groundRay = new Ray(Vec3.Zero + new Vec3(0, 0.2f, 0), Vec3.AngleXZ(Time.Totalf * 90, -2).Normalized());

        Lines.Add(groundRay.position, groundRay.position + groundRay.direction * 0.1f, new Color32(255, 0, 0, 255), 2 * Units.mm2m);
        planeMesh.Draw(material, Matrix.TRS(Vec3.Zero, Quat.LookDir(ground.normal), 0.25f), colObj);
        if (groundRay.Intersect(ground, out Vec3 groundAt))
        {
            sphereMesh.Draw(material, Matrix.TS(groundAt, 0.02f), colIntersect);
        }

        UI.AffordanceEnd();

        if (Tests.IsTesting)
        {
            Renderer.Screenshot(posePlaneRay.position + new Vec3(0.0f, 0.3f, 0.15f), posePlaneRay.position + Vec3.Up * 0.1f, 400, 400, "../../../docs/img/screenshots/RayIntersectPlane.jpg");
        }

        // Line and Plane
        bool linePlaneActive = UI.AffordanceBegin("LinePlane", ref poseLinePlane, new Bounds(Vec3.One * 0.4f));

        boundsMesh.Draw(boundsMat, Matrix.TS(Vec3.Zero, 0.4f), linePlaneActive ? active : notActive);

        Plane groundLinePlane = new Plane(Vec3.Zero, new Vec3(1, 2, 0));
        Ray   groundLineRay   = new Ray(Vec3.Zero + new Vec3(0, 0.25f, 0), Vec3.AngleXZ(Time.Totalf * 90, -2).Normalized());
        Vec3  groundLineP1    = groundLineRay.position + groundLineRay.direction * (SKMath.Cos(Time.Totalf * 3) + 1) * 0.2f;
        Vec3  groundLineP2    = groundLineRay.position + groundLineRay.direction * ((SKMath.Cos(Time.Totalf * 3) + 1) * 0.2f + 0.1f);

        Lines.Add(groundLineP1, groundLineP2, colTest, 2 * Units.mm2m);
        sphereMesh.Draw(material, Matrix.TS(groundLineP1, 0.01f), colTest);
        sphereMesh.Draw(material, Matrix.TS(groundLineP2, 0.01f), colTest);
        bool groundLineIntersects = groundLinePlane.Intersect(groundLineP1, groundLineP2, out Vec3 groundLineAt);

        planeMesh.Draw(material, Matrix.TRS(Vec3.Zero, Quat.LookDir(groundLinePlane.normal), 0.25f), groundLineIntersects? colIntersect : colObj);
        if (groundLineIntersects)
        {
            sphereMesh.Draw(material, Matrix.TS(groundLineAt, 0.02f), colIntersect);
        }

        UI.AffordanceEnd();

        if (Tests.IsTesting)
        {
            Renderer.Screenshot(poseLinePlane.position + new Vec3(0.0f, 0.3f, 0.15f), poseLinePlane.position + Vec3.Up * 0.1f, 400, 400, "../../../docs/img/screenshots/LineIntersectPlane.jpg");
        }

        // Sphere and Ray
        bool sphereRayActive = UI.AffordanceBegin("SphereRay", ref poseSphereRay, new Bounds(Vec3.One * 0.4f));

        boundsMesh.Draw(boundsMat, Matrix.TS(Vec3.Zero, 0.4f), sphereRayActive ? active : notActive);

        Sphere sphere    = new Sphere(Vec3.Zero, 0.25f);
        Vec3   sphereDir = Vec3.AngleXZ(Time.Totalf * 90, SKMath.Cos(Time.Totalf * 3) * 1.5f + 0.1f).Normalized();
        Ray    sphereRay = new Ray(sphere.center - sphereDir * 0.35f, sphereDir);

        Lines.Add(sphereRay.position, sphereRay.position + sphereRay.direction * 0.1f, colTest, 2 * Units.mm2m);
        if (sphereRay.Intersect(sphere, out Vec3 sphereAt))
        {
            sphereMesh.Draw(material, Matrix.TS(sphereAt, 0.02f), colIntersect);
        }
        sphereMesh.Draw(material, Matrix.TS(sphere.center, 0.25f), colObj);

        UI.AffordanceEnd();

        if (Tests.IsTesting)
        {
            Renderer.Screenshot(poseSphereRay.position + new Vec3(0.0f, 0.3f, 0.15f), poseSphereRay.position, 400, 400, "../../../docs/img/screenshots/RayIntersectSphere.jpg");
        }

        // Bounds and Ray
        bool boundsRayActive = UI.AffordanceBegin("BoundsRay", ref poseBoundsRay, new Bounds(Vec3.One * 0.4f));

        boundsMesh.Draw(boundsMat, Matrix.TS(Vec3.Zero, 0.4f), boundsRayActive ? active : notActive);

        Bounds bounds    = new Bounds(Vec3.Zero, Vec3.One * 0.25f);
        Vec3   boundsDir = Vec3.AngleXZ(Time.Totalf * 90, SKMath.Cos(Time.Totalf * 3) * 1.5f).Normalized();
        Ray    boundsRay = new Ray(bounds.center - boundsDir * 0.35f, boundsDir);

        Lines.Add(boundsRay.position, boundsRay.position + boundsRay.direction * 0.1f, colTest, 2 * Units.mm2m);
        if (boundsRay.Intersect(bounds, out Vec3 boundsAt))
        {
            sphereMesh.Draw(material, Matrix.TS(boundsAt, 0.02f), colIntersect);
        }
        cubeMesh.Draw(material, Matrix.TS(bounds.center, 0.25f), colObj);

        UI.AffordanceEnd();

        if (Tests.IsTesting)
        {
            Renderer.Screenshot(poseBoundsRay.position + new Vec3(0.0f, 0.3f, 0.15f), poseBoundsRay.position, 400, 400, "../../../docs/img/screenshots/RayIntersectBounds.jpg");
        }

        // Bounds and Line
        bool boundsLineActive = UI.AffordanceBegin("BoundsLine", ref poseBoundsLine, new Bounds(Vec3.One * 0.4f));

        boundsMesh.Draw(boundsMat, Matrix.TS(Vec3.Zero, 0.4f), boundsLineActive ? active : notActive);

        Bounds boundsLine   = new Bounds(Vec3.Zero, Vec3.One * 0.25f);
        Vec3   boundsLineP1 = boundsLine.center + Vec3.AngleXZ(Time.Totalf * 45, SKMath.Cos(Time.Totalf * 3)) * 0.35f;
        Vec3   boundsLineP2 = boundsLine.center + Vec3.AngleXZ(Time.Totalf * 90, SKMath.Cos(Time.Totalf * 6)) * SKMath.Cos(Time.Totalf) * 0.35f;

        Lines.Add(boundsLineP1, boundsLineP2, colTest, 2 * Units.mm2m);
        sphereMesh.Draw(material, Matrix.TS(boundsLineP1, 0.01f), colTest);
        sphereMesh.Draw(material, Matrix.TS(boundsLineP2, 0.01f), colTest);
        cubeMesh.Draw(material, Matrix.TS(boundsLine.center, 0.25f),
                      boundsLine.Contains(boundsLineP1, boundsLineP2) ? colIntersect : colObj);

        UI.AffordanceEnd();

        if (Tests.IsTesting)
        {
            Renderer.Screenshot(poseBoundsLine.position + new Vec3(0.0f, 0.3f, 0.15f), poseBoundsLine.position, 400, 400, "../../../docs/img/screenshots/LineIntersectBounds.jpg");
        }

        // Cross product
        bool crossActive = UI.AffordanceBegin("Cross", ref poseCross, new Bounds(Vec3.One * 0.4f));

        boundsMesh.Draw(boundsMat, Matrix.TS(Vec3.Zero, 0.4f), crossActive ? active : notActive);

        Vec3 crossStart = Vec3.Zero;
        //Vec3 right      = Vec3.Cross(Vec3.Forward, Vec3.Up); // These are the same!
        Vec3 right = Vec3.PerpendicularRight(Vec3.Forward, Vec3.Up);

        Lines.Add(crossStart, crossStart + Vec3.Up * 0.1f, new Color32(255, 255, 255, 255), 2 * Units.mm2m);
        Lines.Add(crossStart, crossStart + Vec3.Forward * 0.1f, new Color32(255, 255, 255, 255), 2 * Units.mm2m);
        Lines.Add(crossStart, crossStart + right * 0.1f, new Color32(0, 255, 0, 255), 2 * Units.mm2m);
        Text.Add("Up", Matrix.TRS(crossStart + Vec3.Up * 0.1f, Quat.LookDir(-Vec3.Forward), 1), TextAlign.XCenter | TextAlign.YBottom);
        Text.Add("Fwd", Matrix.TRS(crossStart + Vec3.Forward * 0.1f, Quat.LookDir(-Vec3.Forward), 1), TextAlign.XCenter | TextAlign.YBottom);
        Text.Add("Vec3.Cross(Fwd,Up)", Matrix.TRS(crossStart + right * 0.1f, Quat.LookDir(-Vec3.Forward), 1), TextAlign.XCenter | TextAlign.YBottom);

        UI.AffordanceEnd();

        if (Tests.IsTesting)
        {
            Renderer.Screenshot(poseCross.position + new Vec3(0.075f, 0.1f, 0.15f), poseCross.position + new Vec3(0.075f, 0, 0), 400, 400, "../../../docs/img/screenshots/CrossProduct.jpg");
        }
    }
Exemplo n.º 41
0
 public void add(string type, Line line, Position position = null, int layer = 0)
 {
     Lines lines = new Lines();
     if (line != null)
     {
         lines.Add(new Line(line));
     }
     this.add(type, null, lines, position, layer);
 }
        public override void Translating()
        {
            if (ObjectDefinition.Namespaces.Count > 0)
            {
                foreach (var import in ObjectDefinition.Namespaces)
                {
                    Lines.Add(new CodeLine("import {0};", import));
                }

                Lines.Add(new CodeLine());
            }

            var start = 0;

            if (!string.IsNullOrEmpty(ObjectDefinition.Namespace))
            {
                Lines.Add(new CodeLine("namespace {0} {1}", ObjectDefinition.Namespace, "{"));

                start = 1;
            }

            this.AddAttributes(start);

            var classDeclaration = new List <string>
            {
                ObjectDefinition.Export ? "export" : string.Empty,
                "class",
                ObjectDefinition.Name
            };

            if (ObjectDefinition.HasInheritance)
            {
                if (!string.IsNullOrEmpty(ObjectDefinition.BaseClass))
                {
                    classDeclaration.Add("extends");
                    classDeclaration.Add(ObjectDefinition.BaseClass);
                }

                if (ObjectDefinition.Implements.Count > 0)
                {
                    classDeclaration.Add("implements");
                    classDeclaration.Add(string.Join(", ", ObjectDefinition.Implements));
                }
            }

            classDeclaration.Add("{");

            Lines.Add(new CodeLine("{0}{1}", Indent(start), string.Join(" ", classDeclaration)));

            if (ObjectDefinition.Fields.Count > 0)
            {
                for (var i = 0; i < ObjectDefinition.Fields.Count; i++)
                {
                    var field = ObjectDefinition.Fields[i];

                    var fieldDefinition = new List <string>
                    {
                        field.AccessModifier.ToString().ToLower()
                    };

                    if (field.IsStatic)
                    {
                        fieldDefinition.Add("static");
                    }

                    if (field.IsReadOnly)
                    {
                        fieldDefinition.Add("readonly");
                    }

                    fieldDefinition.Add(field.Name);
                    fieldDefinition.Add(":");
                    fieldDefinition.Add(field.Type);

                    if (!string.IsNullOrEmpty(field.Value))
                    {
                        fieldDefinition.Add("=");
                        fieldDefinition.Add(field.Value);
                    }

                    Lines.Add(new CodeLine("{0}{1};", Indent(start + 1), string.Join(" ", fieldDefinition)));
                }
            }

            if (ObjectDefinition.Constructors.Count > 0)
            {
                Lines.Add(new CodeLine());

                var constructor = ObjectDefinition.Constructors.First();

                var parameters = constructor.Parameters.Select(item => string.Format("{0} {1}: {2}", item.AccessModifier.ToString().ToLower(), item.Name, item.Type)).ToList();

                Lines.Add(new CodeLine("{0}constructor({1}) {2}", Indent(start + 1), parameters.Count == 0 ? string.Empty : string.Join(", ", parameters), "{"));

                foreach (var line in constructor.Lines)
                {
                    Lines.Add(new CodeLine("{0}{1}", Indent(start + 2), line.ToString()));
                }

                Lines.Add(new CodeLine("{0}{1}", Indent(start + 1), "}"));
            }

            if (ObjectDefinition.Properties.Count > 0)
            {
                Lines.Add(new CodeLine());

                for (var i = 0; i < ObjectDefinition.Properties.Count; i++)
                {
                    var property = ObjectDefinition.Properties[i];

                    if (property.IsAutomatic)
                    {
                        var fieldName = NamingConvention.GetFieldName(property.Name);

                        Lines.Add(new CodeLine("{0}{1} get {2}(): {3} {4}", Indent(start + 1), property.AccessModifier.ToString().ToLower(), property.Name, property.Type, "{"));

                        Lines.Add(new CodeLine("{0}return this.{1};", Indent(start + 2), fieldName));

                        Lines.Add(new CodeLine("{0}{1}", Indent(start + 1), "}"));

                        Lines.Add(new CodeLine());

                        Lines.Add(new CodeLine("{0}{1} set {2}(value: {3}) {4}", Indent(start + 1), property.AccessModifier.ToString().ToLower(), property.Name, property.Type, "{"));

                        Lines.Add(new CodeLine("{0}this.{1} = value;", Indent(start + 2), fieldName));

                        Lines.Add(new CodeLine("{0}{1}", Indent(start + 1), "}"));

                        if (i < ObjectDefinition.Properties.Count - 1)
                        {
                            Lines.Add(new CodeLine());
                        }
                    }
                    else
                    {
                        Lines.Add(new CodeLine("{0}{1} get {2}(): {3} {4}", Indent(start + 1), property.AccessModifier.ToString().ToLower(), property.Name, property.Type, "{"));

                        foreach (var line in property.GetBody)
                        {
                            var commentCast = line as CommentLine;

                            if (commentCast == null)
                            {
                                Lines.Add(new CodeLine("{0}{1}", Indent(start + line.Indent), line.Content));
                            }
                            else
                            {
                                Lines.Add(new CodeLine("{0}{1}", Indent(start + line.Indent), GetComment(line.Content)));
                            }
                        }

                        Lines.Add(new CodeLine("{0}{1}", Indent(start + 1), "}"));

                        Lines.Add(new CodeLine());

                        Lines.Add(new CodeLine("{0}{1} set {2}(value: {3}) {4}", Indent(start + 1), property.AccessModifier.ToString().ToLower(), property.Name, property.Type, "{"));

                        foreach (var line in property.SetBody)
                        {
                            var commentCast = line as CommentLine;

                            if (commentCast == null)
                            {
                                Lines.Add(new CodeLine("{0}{1}", Indent(start + line.Indent), line.Content));
                            }
                            else
                            {
                                Lines.Add(new CodeLine("{0}{1}", Indent(start + line.Indent), GetComment(line.Content)));
                            }
                        }

                        Lines.Add(new CodeLine("{0}{1}", Indent(start + 1), "}"));

                        if (i < ObjectDefinition.Properties.Count - 1)
                        {
                            Lines.Add(new CodeLine());
                        }
                    }
                }
            }

            if (ObjectDefinition.Methods.Count > 0)
            {
                Lines.Add(new CodeLine());

                for (var i = 0; i < ObjectDefinition.Methods.Count; i++)
                {
                    var method = ObjectDefinition.Methods[i];

                    var parameters = method.Parameters.Select(item => string.Format("{0}: {1}", item.Name, item.Type));

                    Lines.Add(
                        new CodeLine("{0}{1} {2}({3}): {4} {5}", Indent(start + 1), method.AccessModifier.ToString().ToLower(), method.Name, method.Parameters.Count == 0 ? string.Empty : string.Join(", ", method.Parameters.Select(item => string.Format("{0}: {1}", item.Name, item.Type))), method.Type, "{")
                        );

                    foreach (var line in method.Lines)
                    {
                        if (line is CodeLine)
                        {
                            Lines.Add(new CodeLine("{0}{1}", Indent(start + 2 + line.Indent), line.Content));
                        }
                        else if (line is CommentLine)
                        {
                            Lines.Add(new CodeLine("{0}{1}", Indent(start + 2 + line.Indent), GetComment(line.Content)));
                        }
                        else if (line is TodoLine)
                        {
                            Lines.Add(new CodeLine("{0}{1}", Indent(start + 2 + line.Indent), GetTodo(line.Content)));
                        }
                    }

                    Lines.Add(new CodeLine("{0}{1}", Indent(start + 1), "}"));

                    if (i < ObjectDefinition.Methods.Count - 1)
                    {
                        Lines.Add(new CodeLine());
                    }
                }
            }

            Lines.Add(new CodeLine("{0}{1}", Indent(start), "}"));

            if (!string.IsNullOrEmpty(ObjectDefinition.Namespace))
            {
                Lines.Add(new CodeLine("{0}", "}"));
            }
        }
Exemplo n.º 43
0
        public bool doUndo(DiagramView view = null)
        {
            if (operations.Count() == 0)
            {
                return false;
            }

            int group = 0;

            bool result = false;

            do
            {
                UndoOperation operation = operations.First();

                // first restore position where change occurred
                if (view != null && !view.isOnPosition(operation.position, operation.layer))
                {
                    view.goToShift(operation.position);
                    view.goToLayer(operation.layer);
                    view.Invalidate();
                    return false;
                }

                // process all operations in same group
                if (group != 0 && operation.group != group)
                {
                    group = 0;
                    break;
                }

                group = operation.group;

                if (operation.type == "delete")
                {
                    this.doUndoDelete(operation);
                    reverseOperations.Push(operation);
                }

                if (operation.type == "create")
                {
                    this.doUndoCreate(operation);
                    reverseOperations.Push(operation);
                }

                if (operation.type == "edit" ||
                    operation.type == "move" ||
                    operation.type == "changeLineColor" ||
                    operation.type == "changeLineWidth" ||
                    operation.type == "changeNodeColor"
                )
                {
                    Nodes nodes = new Nodes();
                    foreach (Node node in operation.nodes)
                    {
                        nodes.Add(this.diagram.GetNodeByID(node.id));
                    }

                    Lines lines = new Lines();
                    foreach (Line line in operation.lines)
                    {
                        lines.Add(this.diagram.getLine(line.start, line.end));
                    }

                    UndoOperation roperation = new UndoOperation(
                        operation.type,
                        nodes,
                        lines,
                        operation.group,
                        operation.position,
                        operation.layer
                    );
                    reverseOperations.Push(roperation);
                    this.doUndoEdit(operation);
                }

                operations.Pop();
                result = true;
            } while (group != 0 && operations.Count() > 0);

            if (result)
            {
                this.saved--;
                if (!this.saveLost && this.saved == 0)
                {
                    this.diagram.restoresave();
                }
                else
                {
                    this.diagram.unsave();
                }
            }

            return result;
        }
Exemplo n.º 44
0
        public DiagramBlock getPartOfDiagram(Nodes nodes)
        {
            Nodes allNodes = new Nodes();
            Lines lines = new Lines();

            foreach (Node node in nodes)
            {
                allNodes.Add(node);
            }

            if (allNodes.Count() > 0)
            {
                Nodes subnodes = new Nodes();

                foreach (Node node in allNodes)
                {
                    getLayerNodes(node, subnodes);
                }

                foreach (Node node in subnodes)
                {
                    allNodes.Add(node);
                }

                foreach (Line li in this.getAllLines())
                {
                    foreach (Node recstart in allNodes)
                    {
                        if (li.start == recstart.id)
                        {
                            foreach (Node recend in allNodes)
                            {
                                if (li.end == recend.id)
                                {
                                    lines.Add(li);
                                }
                            }
                        }
                    }
                }
            }

            return new DiagramBlock(allNodes, lines);
        }
Exemplo n.º 45
0
        // all nodes contain nodes and all sublayer nodes, allLines contain all node lines and all sublayer lines
        public void getAllNodesAndLines(Nodes nodes, ref Nodes allNodes, ref Lines allLines)
        {
            foreach (Node node in nodes)
            {
                // add node itself to output
                allNodes.Add(node);

                if (node.haslayer)
                {
                    Layer layer = this.getLayer(node.id);
                    getAllNodesAndLines(layer.nodes, ref allNodes, ref allLines);
                }

                Lines lines = getAllLinesFromNode(node);
                foreach (Line line in lines)
                {
                    bool found = false;

                    foreach (Line subline in allLines)
                    {
                        if (line.start == subline.start && line.end == subline.end)
                        {
                            found = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        allLines.Add(line);
                    }
                }
            }
        }
Exemplo n.º 46
0
 // --------------------------------------------------------------------------------------------------------------------------
 public void AddLine(CSVLine line)
 {
     Lines.Add(line);
 }
        public override void Translating()
        {
            if (ObjectDefinition.Namespaces.Count > 0)
            {
                foreach (var import in ObjectDefinition.Namespaces)
                {
                    Lines.Add(new CodeLine("import {0};", import));
                }

                Lines.Add(new CodeLine());
            }

            var start = 0;

            if (!string.IsNullOrEmpty(ObjectDefinition.Namespace))
            {
                Lines.Add(new CodeLine("namespace {0} {1}", ObjectDefinition.Namespace, "{"));

                start = 1;
            }

            this.AddAttributes(start);

            if (ObjectDefinition.Documentation.HasSummary)
            {
                Lines.Add(new CodeLine("{0}/** {1} */", Indent(start), ObjectDefinition.Documentation.Summary));
            }

            var declaration = new List <string>
            {
                string.Format("{0}", ObjectDefinition.Export ? "export" : string.Empty),
                "interface",
                ObjectDefinition.Name
            };

            if (ObjectDefinition.HasInheritance && ObjectDefinition.Implements.Count > 0)
            {
                declaration.Add("implements");
                declaration.Add(string.Join(", ", ObjectDefinition.Implements));
            }

            declaration.Add("{");

            Lines.Add(new CodeLine("{0}{1}", Indent(start), string.Join(" ", declaration)));

            if (ObjectDefinition.Properties.Count > 0)
            {
                foreach (var property in ObjectDefinition.Properties)
                {
                    if (property.Documentation.HasSummary)
                    {
                        Lines.Add(new CommentLine("{0}/**", Indent(start + 1)));

                        Lines.Add(new CommentLine("{0}* {1}", Indent(start + 1), property.Documentation.Summary));

                        Lines.Add(new CommentLine("{0}*/", Indent(start + 1)));
                    }

                    Lines.Add(new CodeLine("{0}{1}: {2};", Indent(start + 1), property.Name, property.Type));
                }
            }

            if (ObjectDefinition.Methods.Count > 0)
            {
                foreach (var method in ObjectDefinition.Methods)
                {
                    if (method.Documentation.HasSummary)
                    {
                        Lines.Add(new CommentLine("{0}/**", Indent(start + 1)));

                        Lines.Add(new CommentLine("{0}* {1}", Indent(start + 1), method.Documentation.Summary));

                        foreach (var parameter in method.Parameters)
                        {
                            Lines.Add(new CodeLine("{0}* @{1} {2}", Indent(start + 1), parameter.Name, parameter.Documentation.Summary));
                        }

                        Lines.Add(new CommentLine("{0}*/", Indent(start + 1)));
                    }

                    var parameters = string.Join(", ", method.Parameters.Select(item => string.Format("{0}: {1}", item.Name, item.Type)));

                    Lines.Add(new CodeLine("{0}{1}({2}): {3};", Indent(start + 1), method.Name, method.Parameters.Count == 0 ? string.Empty : parameters, method.Type));
                }
            }

            Lines.Add(new CodeLine("{0}{1}", Indent(start), "}"));

            if (!string.IsNullOrEmpty(ObjectDefinition.Namespace))
            {
                Lines.Add(new CodeLine("}"));
            }
        }
Exemplo n.º 48
0
        // XML LOAD inner part of diagram file. If file is invalid return false
        public bool LoadInnerXML(string xml)
        {
            string FontDefaultString = TypeDescriptor.GetConverter(typeof(Font)).ConvertToString(this.FontDefault);

            XmlReaderSettings xws = new XmlReaderSettings();
            xws.CheckCharacters = false;

            Nodes nodes = new Nodes();
            Lines lines = new Lines();

            try
            {
                using (XmlReader xr = XmlReader.Create(new StringReader(xml), xws))
                {

                    XElement root = XElement.Load(xr);
                    foreach (XElement diagram in root.Elements())
                    {
                        if (diagram.HasElements)
                        {

                            if (diagram.Name.ToString() == "option") // [options] [config]
                            {
                                foreach (XElement el in diagram.Descendants())
                                {
                                    try
                                    {
                                        if (el.Name.ToString() == "shiftx")
                                        {
                                            this.options.homePosition.x = Int32.Parse(el.Value);
                                        }

                                        if (el.Name.ToString() == "shifty")
                                        {
                                            this.options.homePosition.y = Int32.Parse(el.Value);
                                        }

                                        if (el.Name.ToString() == "homelayer")
                                        {
                                            options.homeLayer = Int32.Parse(el.Value);
                                        }

                                        if (el.Name.ToString() == "endlayer")
                                        {
                                            options.endLayer = Int32.Parse(el.Value);
                                        }

                                        if (el.Name.ToString() == "endPositionx")
                                        {
                                            this.options.endPosition.x = Int32.Parse(el.Value);
                                        }

                                        if (el.Name.ToString() == "endPositiony")
                                        {
                                            this.options.endPosition.y = Int32.Parse(el.Value);
                                        }

                                        if (el.Name.ToString() == "startShiftX")
                                        {
                                            options.homePosition.x = Int32.Parse(el.Value);
                                        }

                                        if (el.Name.ToString() == "startShiftY")
                                        {
                                            options.homePosition.y = Int32.Parse(el.Value);
                                        }

                                        if (el.Name.ToString() == "diagramreadonly")
                                        {
                                            this.options.readOnly = bool.Parse(el.Value);
                                        }

                                        if (el.Name.ToString() == "grid")
                                        {
                                            this.options.grid = bool.Parse(el.Value);
                                        }

                                        if (el.Name.ToString() == "borders")
                                        {
                                            this.options.borders = bool.Parse(el.Value);
                                        }

                                        if (el.Name.ToString() == "defaultfont")
                                        {
                                            if (el.Attribute("type").Value == "font")
                                            {
                                                this.FontDefault = Fonts.XmlToFont(el);
                                            }
                                            else
                                            {
                                                if (FontDefaultString != el.Value)
                                                {
                                                    this.FontDefault = (Font)TypeDescriptor.GetConverter(typeof(Font)).ConvertFromString(el.Value);
                                                }
                                            }
                                        }

                                        if (el.Name.ToString() == "coordinates")
                                        {
                                            this.options.coordinates = bool.Parse(el.Value);
                                        }

                                        if (el.Name.ToString() == "firstLayereShift.x")
                                        {
                                            this.options.firstLayereShift.x = Int32.Parse(el.Value);
                                        }

                                        if (el.Name.ToString() == "firstLayereShift.y")
                                        {
                                            this.options.firstLayereShift.y = Int32.Parse(el.Value);
                                        }

                                        if (el.Name.ToString() == "openLayerInNewView")
                                        {
                                            this.options.openLayerInNewView = bool.Parse(el.Value);
                                        }

                                        if (el.Name.ToString() == "window.position.restore")
                                        {
                                            this.options.restoreWindow = bool.Parse(el.Value);
                                        }

                                        if (el.Name.ToString() == "window.position.x")
                                        {
                                            this.options.Left = Int32.Parse(el.Value);
                                        }

                                        if (el.Name.ToString() == "window.position.y")
                                        {
                                            this.options.Top = Int32.Parse(el.Value);
                                        }

                                        if (el.Name.ToString() == "window.position.width")
                                        {
                                            this.options.Width = Int32.Parse(el.Value);
                                        }

                                        if (el.Name.ToString() == "window.position.height")
                                        {
                                            this.options.Height = Int32.Parse(el.Value);
                                        }

                                        if (el.Name.ToString() == "window.state")
                                        {
                                            this.options.WindowState = Int32.Parse(el.Value);
                                        }

                                        if (el.Name.ToString() == "icon")
                                        {
                                            this.options.icon = el.Value;
                                        }

                                        if (el.Name.ToString() == "backgroundImage")
                                        {
                                            this.options.backgroundImage = Media.StringToImage(el.Value);
                                        }

                                    }
                                    catch (Exception ex)
                                    {
                                        Program.log.write("load xml diagram options: " + ex.Message);
                                    }
                                }
                            }

                            if (diagram.Name.ToString() == "rectangles")
                            {
                                foreach (XElement block in diagram.Descendants())
                                {

                                    if (block.Name.ToString() == "rectangle")
                                    {
                                        Node R = new Node();
                                        R.font = this.FontDefault;

                                        foreach (XElement el in block.Descendants())
                                        {
                                            try
                                            {
                                                if (el.Name.ToString() == "id")
                                                {
                                                    R.id = Int32.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "font")
                                                {
                                                    if (el.Attribute("type").Value == "font")
                                                    {
                                                        R.font = Fonts.XmlToFont(el);
                                                    }
                                                    else
                                                    {
                                                        if (FontDefaultString != el.Value)
                                                        {
                                                            R.font = (Font)TypeDescriptor.GetConverter(typeof(Font)).ConvertFromString(el.Value);
                                                        }
                                                    }
                                                }

                                                if (el.Name.ToString() == "fontcolor")
                                                {
                                                    R.fontcolor.set(el.Value.ToString());
                                                }

                                                if (el.Name.ToString() == "text")
                                                {
                                                    R.name = el.Value;
                                                }

                                                if (el.Name.ToString() == "note")
                                                {
                                                    R.note = el.Value;
                                                }

                                                if (el.Name.ToString() == "link")
                                                {
                                                    R.link = el.Value;
                                                }

                                                if (el.Name.ToString() == "scriptid")
                                                {
                                                    R.scriptid = el.Value;
                                                }

                                                if (el.Name.ToString() == "shortcut")
                                                {
                                                    R.shortcut = Int32.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "mark")
                                                {
                                                    R.mark = bool.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "attachment")
                                                {
                                                    R.attachment = el.Value;
                                                }

                                                if (el.Name.ToString() == "layer")
                                                {
                                                    R.layer = Int32.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "haslayer")
                                                {
                                                    R.haslayer = bool.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "layershiftx")
                                                {
                                                    R.layerShift.x = Int32.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "layershifty")
                                                {
                                                    R.layerShift.y = Int32.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "x")
                                                {
                                                    R.position.x = Int32.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "y")
                                                {
                                                    R.position.y = Int32.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "width")
                                                {
                                                    R.width = Int32.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "height")
                                                {
                                                    R.height = Int32.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "color")
                                                {
                                                    R.color.set(el.Value.ToString());
                                                }

                                                if (el.Name.ToString() == "transparent")
                                                {
                                                    R.transparent = bool.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "embeddedimage")
                                                {
                                                    R.embeddedimage = bool.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "imagedata")
                                                {
                                                    R.image = Media.StringToBitmap(el.Value);
                                                    R.height = R.image.Height;
                                                    R.width = R.image.Width;
                                                    R.isimage = true;
                                                }

                                                if (el.Name.ToString() == "image")
                                                {
                                                    R.imagepath = el.Value.ToString();
                                                    R.loadImage();
                                                }

                                                if (el.Name.ToString() == "timecreate")
                                                {
                                                    R.timecreate = el.Value;
                                                }

                                                if (el.Name.ToString() == "timemodify")
                                                {
                                                    R.timemodify = el.Value;
                                                }

                                                if (el.Name.ToString() == "protect")
                                                {
                                                    R.protect = bool.Parse(el.Value);
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                Program.log.write("load xml nodes error: " + ex.Message);
                                            }
                                        }
                                        nodes.Add(R);
                                    }
                                }
                            }

                            if (diagram.Name.ToString() == "lines")
                            {
                                foreach (XElement block in diagram.Descendants())
                                {
                                    if (block.Name.ToString() == "line")
                                    {
                                        Line L = new Line();
                                        L.layer = -1; // for identification unset layers

                                        foreach (XElement el in block.Descendants())
                                        {
                                            try
                                            {
                                                if (el.Name.ToString() == "start")
                                                {
                                                    L.start = Int32.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "end")
                                                {
                                                    L.end = Int32.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "arrow")
                                                {
                                                    L.arrow = el.Value == "1" ? true : false;
                                                }

                                                if (el.Name.ToString() == "color")
                                                {
                                                    L.color.set(el.Value.ToString());
                                                }

                                                if (el.Name.ToString() == "width")
                                                {
                                                    L.width = Int32.Parse(el.Value);
                                                }

                                                if (el.Name.ToString() == "layer")
                                                {
                                                    L.layer = Int32.Parse(el.Value);
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                Program.log.write("load xml lines error: " + ex.Message);
                                            }
                                        }

                                        lines.Add(L);
                                    }

                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Translations.fileHasWrongFormat);
                Program.log.write("load xml error: " + ex.Message);
                this.CloseFile();
                return false;
            }

            int newWidth = 0;
            int newHeight = 0;

            Nodes nodesReordered = new Nodes(); // order nodes parent first (layer must exist when sub node is created)
            this.nodesReorderNodes(0, null, nodes, nodesReordered);

            foreach (Node rec in nodesReordered) // Loop through List with foreach
            {
                if (!rec.isimage)
                {
                    SizeF s = rec.measure();
                    newWidth = (int)s.Width;
                    newHeight = (int)s.Height;

                    // font change correction > center node
                    if (rec.width != 0 && newWidth != rec.width)
                    {
                        rec.position.x += (rec.width - newWidth) / 2;
                    }

                    if (rec.height != 0 && newHeight != rec.height)
                    {
                        rec.position.y += (rec.height - newHeight) / 2;
                    }

                    rec.resize();

                }

                this.layers.addNode(rec);
            }

            this.layers.setLayersParentsReferences();

            foreach (Line line in lines)
            {
                this.Connect(
                    this.layers.getNode(line.start),
                    this.layers.getNode(line.end),
                    line.arrow,
                    line.color,
                    line.width
                );
            }

            return true;
        }