Ejemplo n.º 1
0
 public static void NodesBeforeSelfBeforeAndAfter()
 {
     XText aText = new XText("a"), bText = new XText("b");
     XElement a = new XElement("A", aText, bText);
     IEnumerable<XNode> nodes = bText.NodesBeforeSelf();
     Assert.Equal(1, nodes.Count());
     aText.Remove();
     Assert.Equal(0, nodes.Count());
 }
Ejemplo n.º 2
0
 public static void AncestorsWithXNameBeforeAndAfter()
 {
     XText aText = new XText("a"), bText = new XText("b");
     XElement a = new XElement("A", aText), b = new XElement("B", bText);
     a.Add(b);
     IEnumerable<XElement> nodes = bText.Ancestors("B");
     Assert.Equal(1, nodes.Count());
     bText.Remove(); a.Add(bText);
     Assert.Equal(0, nodes.Count());
 }
Ejemplo n.º 3
0
 public static void ElementsAfterSelfWithXNameBeforeAndAfter()
 {
     XText aText = new XText("a"), bText = new XText("b");
     XElement a = new XElement("A", aText), b = new XElement("B", bText);
     a.Add(b);
     IEnumerable<XElement> nodes = aText.ElementsAfterSelf("B");
     Assert.Equal(1, nodes.Count());
     b.ReplaceWith(a);
     Assert.Equal(0, nodes.Count());
 }
            public XTextChangedCache(XText newText)
            {
                // 一致しない場合はとりあえず放置.
                if (newText.Parent == currentParent)
                {
                    this.OldValue = currentOldValue;
                    this.Parent = newText.Parent;
                    this.NewValue = newText.Value;

                    currentParent = null;
                    currentOldValue = null;
                }
            }
Ejemplo n.º 5
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="x"></param>
 /// <param name="y"></param>
 public override void LeftDown(double x, double y)
 {
     double sx = _editor.Project.Options.SnapToGrid ? Editor.Snap(x, _editor.Project.Options.SnapX) : x;
     double sy = _editor.Project.Options.SnapToGrid ? Editor.Snap(y, _editor.Project.Options.SnapY) : y;
     switch (_currentState)
     {
         case State.None:
             {
                 _shape = XText.Create(
                     sx, sy,
                     _editor.Project.CurrentStyleLibrary.CurrentStyle,
                     _editor.Project.Options.PointShape,
                     "Text",
                     _editor.Project.Options.DefaultIsStroked);
                 if (_editor.Project.Options.TryToConnect)
                 {
                     TryToConnectTopLeft(_shape as XText, sx, sy);
                 }
                 _editor.Project.CurrentContainer.WorkingLayer.Shapes = _editor.Project.CurrentContainer.WorkingLayer.Shapes.Add(_shape);
                 _editor.Project.CurrentContainer.WorkingLayer.Invalidate();
                 ToStateOne();
                 Move(_shape);
                 _editor.Project.CurrentContainer.HelperLayer.Invalidate();
                 _currentState = State.One;
                 _editor.CancelAvailable = true;
             }
             break;
         case State.One:
             {
                 var text = _shape as XText;
                 if (text != null)
                 {
                     text.BottomRight.X = sx;
                     text.BottomRight.Y = sy;
                     if (_editor.Project.Options.TryToConnect)
                     {
                         TryToConnectBottomRight(_shape as XText, sx, sy);
                     }
                     _editor.Project.CurrentContainer.WorkingLayer.Shapes = _editor.Project.CurrentContainer.WorkingLayer.Shapes.Remove(_shape);
                     Remove();
                     Finalize(_shape);
                     _editor.AddWithHistory(_shape);
                     _currentState = State.None;
                     _editor.CancelAvailable = false;
                 }
             }
             break;
     }
 }
Ejemplo n.º 6
0
 private IText ReadText()
 {
     var text = new XText()
     {
         Id = _reader.ReadInt32(),
         Point1 = ReadPoint(),
         Point2 = ReadPoint(),
         HorizontalAlignment = _reader.ReadInt32(),
         VerticalAlignment = _reader.ReadInt32(),
         Size = _reader.ReadDouble(),
         Text = _reader.ReadString(),
         Foreground = ReadColor(),
         Backgroud = ReadColor()
     };
     _natives.Add(text.Id, text);
     return text;
 }
Ejemplo n.º 7
0
 /// <summary>
 /// Initialize <see cref="Text"/> instance from XML Documentation Comments node
 /// (element content or it's part when child elements are in place)
 /// </summary>
 /// <param name="text"><see cref="XText"/> node of XML Documentation Comments</param>
 public Text(XText text) : base(text)
 {
     Content = text.Value;
     Kind    = "Text";
 }
Ejemplo n.º 8
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="text"></param>
 /// <param name="dx"></param>
 /// <param name="dy"></param>
 /// <returns></returns>
 public static Rect2 GetTextBounds(XText text, double dx, double dy)
 {
     return Rect2.Create(text.TopLeft, text.BottomRight, dx, dy);
 }
Ejemplo n.º 9
0
        public void TextVsCData(string value1, string value2, bool checkHashCode)
        {
            XText t1 = new XCData(value1);
            XText t2 = new XText(value2);
            VerifyComparison(checkHashCode, t1, t2);

            XElement e2 = new XElement("p2p", t2);
            e2.Add(t1);
            VerifyComparison(checkHashCode, t1, t2);
        }
Ejemplo n.º 10
0
 public static long ParseLong(this XText e)
 {
     return(ParseLong(e == null ? null : e.Value));
 }
Ejemplo n.º 11
0
 public static DateTime ParseUnixTime(this XText e)
 {
     return(ParseUnixTime(e == null ? null : e.Value));
 }
Ejemplo n.º 12
0
 private static bool AreEqual(XText expected, XText actual)
 {
     return(expected.Value == actual.Value);
 }
Ejemplo n.º 13
0
 public static string ParseString(this XText e)
 {
     return(e == null ? null : ResolveEntity(e.Value));
 }
Ejemplo n.º 14
0
 public XTextWrapper(XText text)
     : base((XObject)text)
 {
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Copy all the elements in A that are not in B to B.
        /// </summary>
        /// <param name="A"></param>
        /// <param name="B"></param>
        public static void CopyTo(this XElement A, XElement B)
        {
            XNode lastB = null, nodeA = null, nodeB = null;

            Action Copy_A_To_B = () =>
            {
                if (null == lastB)
                {
                    B.AddFirst(nodeA);
                }
                else
                {
                    lastB.AddAfterSelf(nodeA);
                }
            };

            var listA = A.Nodes().ToList();
            var listB = B.Nodes().ToList();
            int a, b;

            for (a = 0, b = 0; a < listA.Count && b < listB.Count; a++, b++)
            {
                nodeA = listA[a];
                nodeB = listB[b];

                XElement xA = nodeA as XElement,
                         xB = nodeB as XElement;

                XText tA = nodeA as XText,
                      tB = nodeB as XText;

                if (null != xA && null != xB)
                {
                    if (xA.Name.LocalName == xB.Name.LocalName)
                    {
                        CopyTo(xA, xB);
                    }
                    else
                    {
                        Copy_A_To_B();
                        CopyTo(A, B);                         // Restart this iteration for various reasons such as
                        // the next nodeA might be the same as current nodeB
                        return;
                    }
                }
                else if (null != xA)
                {
                    Copy_A_To_B();
                }
                else if (null != tA && null != tB)
                {
                    if (tA.Value != tB.Value)
                    {
                        tB.Value = tA.Value;
                    }
                }
                else if (null != tA)
                {
                    Copy_A_To_B();
                }

                lastB = nodeB;
            }
            for (; a < listA.Count; a++)
            {
                nodeA = listA[a];
                Copy_A_To_B();
                lastB = null == lastB ? B.FirstNode : lastB.NextNode;
            }
        }
Ejemplo n.º 16
0
 public static string GetXPath(this XObject xobj)
 {
     if (xobj.Parent == null)
     {
         XDocument doc = xobj as XDocument;
         if (doc != null)
         {
             return(".");
         }
         XElement el = xobj as XElement;
         if (el != null)
         {
             return("/" + NameWithPredicate(el));
         }
         XText xt = xobj as XText;
         if (xt != null)
         {
             return(null);
         }
         //
         //the following doesn't work because the XPath data
         //model doesn't include white space text nodes that
         //are children of the document.
         //
         //return
         //    "/" +
         //    (
         //        xt
         //        .Document
         //        .Nodes()
         //        .OfType<XText>()
         //        .Count() != 1 ?
         //        "text()[" +
         //        (xt
         //        .NodesBeforeSelf()
         //        .OfType<XText>()
         //        .Count() + 1) + "]" :
         //        "text()"
         //    );
         //
         XComment com = xobj as XComment;
         if (com != null)
         {
             return
                 ("/" +
                  (
                      com
                      .Document
                      .Nodes()
                      .OfType <XComment>()
                      .Count() != 1 ?
                      "comment()[" +
                      (com
                       .NodesBeforeSelf()
                       .OfType <XComment>()
                       .Count() + 1) +
                      "]" :
                      "comment()"
                  ));
         }
         XProcessingInstruction pi = xobj as XProcessingInstruction;
         if (pi != null)
         {
             return
                 ("/" +
                  (
                      pi.Document.Nodes()
                      .OfType <XProcessingInstruction>()
                      .Count() != 1 ?
                      "processing-instruction()[" +
                      (pi
                       .NodesBeforeSelf()
                       .OfType <XProcessingInstruction>()
                       .Count() + 1) +
                      "]" :
                      "processing-instruction()"
                  ));
         }
         return(null);
     }
     else
     {
         XElement el = xobj as XElement;
         if (el != null)
         {
             return
                 ("/" +
                  el
                  .Ancestors()
                  .InDocumentOrder()
                  .Select(e => NameWithPredicate(e))
                  .StrCat("/") +
                  NameWithPredicate(el));
         }
         XAttribute at = xobj as XAttribute;
         if (at != null)
         {
             return
                 ("/" +
                  at
                  .Parent
                  .AncestorsAndSelf()
                  .InDocumentOrder()
                  .Select(e => NameWithPredicate(e))
                  .StrCat("/") +
                  "@" + GetQName(at));
         }
         XComment com = xobj as XComment;
         if (com != null)
         {
             return
                 ("/" +
                  com
                  .Parent
                  .AncestorsAndSelf()
                  .InDocumentOrder()
                  .Select(e => NameWithPredicate(e))
                  .StrCat("/") +
                  (
                      com
                      .Parent
                      .Nodes()
                      .OfType <XComment>()
                      .Count() != 1 ?
                      "comment()[" +
                      (com
                       .NodesBeforeSelf()
                       .OfType <XComment>()
                       .Count() + 1) + "]" :
                      "comment()"
                  ));
         }
         XCData cd = xobj as XCData;
         if (cd != null)
         {
             return
                 ("/" +
                  cd
                  .Parent
                  .AncestorsAndSelf()
                  .InDocumentOrder()
                  .Select(e => NameWithPredicate(e))
                  .StrCat("/") +
                  (
                      cd
                      .Parent
                      .Nodes()
                      .OfType <XText>()
                      .Count() != 1 ?
                      "text()[" +
                      (cd
                       .NodesBeforeSelf()
                       .OfType <XText>()
                       .Count() + 1) + "]" :
                      "text()"
                  ));
         }
         XText tx = xobj as XText;
         if (tx != null)
         {
             return
                 ("/" +
                  tx
                  .Parent
                  .AncestorsAndSelf()
                  .InDocumentOrder()
                  .Select(e => NameWithPredicate(e))
                  .StrCat("/") +
                  (
                      tx
                      .Parent
                      .Nodes()
                      .OfType <XText>()
                      .Count() != 1 ?
                      "text()[" +
                      (tx
                       .NodesBeforeSelf()
                       .OfType <XText>()
                       .Count() + 1) + "]" :
                      "text()"
                  ));
         }
         XProcessingInstruction pi = xobj as XProcessingInstruction;
         if (pi != null)
         {
             return
                 ("/" +
                  pi
                  .Parent
                  .AncestorsAndSelf()
                  .InDocumentOrder()
                  .Select(e => NameWithPredicate(e))
                  .StrCat("/") +
                  (
                      pi
                      .Parent
                      .Nodes()
                      .OfType <XProcessingInstruction>()
                      .Count() != 1 ?
                      "processing-instruction()[" +
                      (pi
                       .NodesBeforeSelf()
                       .OfType <XProcessingInstruction>()
                       .Count() + 1) + "]" :
                      "processing-instruction()"
                  ));
         }
         return(null);
     }
 }
Ejemplo n.º 17
0
        public void Draw(object ds, XText text, double dx, double dy, ImmutableArray <ShapeProperty> db, Record r)
        {
            var _ds = ds as CanvasDrawingSession;

            var tbind = text.BindToTextProperty(db, r);

            if (string.IsNullOrEmpty(tbind))
            {
                return;
            }

            var brush = ToColor(text.Style.Stroke);

            var fontWeight = FontWeights.Normal;

            if (text.Style.TextStyle.FontStyle.Flags.HasFlag(Core2D.FontStyleFlags.Bold))
            {
                fontWeight = FontWeights.Bold;
            }

            var fontStyle = Windows.UI.Text.FontStyle.Normal;

            if (text.Style.TextStyle.FontStyle.Flags.HasFlag(Core2D.FontStyleFlags.Italic))
            {
                fontStyle = Windows.UI.Text.FontStyle.Italic;
            }

            var format = new CanvasTextFormat()
            {
                FontFamily   = text.Style.TextStyle.FontName,
                FontWeight   = fontWeight,
                FontStyle    = fontStyle,
                FontSize     = (float)text.Style.TextStyle.FontSize,
                WordWrapping = CanvasWordWrapping.NoWrap
            };

            var rect = Rect2.Create(text.TopLeft, text.BottomRight, dx, dy);

            var layout = new CanvasTextLayout(_ds, tbind, format, (float)rect.Width, (float)rect.Height);

            if (text.Style.TextStyle.FontStyle.Flags.HasFlag(Core2D.FontStyleFlags.Underline))
            {
                layout.SetUnderline(0, tbind.Length, true);
            }

            if (text.Style.TextStyle.FontStyle.Flags.HasFlag(Core2D.FontStyleFlags.Strikeout))
            {
                layout.SetStrikethrough(0, tbind.Length, true);
            }

            switch (text.Style.TextStyle.TextHAlignment)
            {
            case TextHAlignment.Left:
                layout.HorizontalAlignment = CanvasHorizontalAlignment.Left;
                break;

            case TextHAlignment.Center:
                layout.HorizontalAlignment = CanvasHorizontalAlignment.Center;
                break;

            case TextHAlignment.Right:
                layout.HorizontalAlignment = CanvasHorizontalAlignment.Right;
                break;
            }

            switch (text.Style.TextStyle.TextVAlignment)
            {
            case TextVAlignment.Top:
                layout.VerticalAlignment = CanvasVerticalAlignment.Top;
                break;

            case TextVAlignment.Center:
                layout.VerticalAlignment = CanvasVerticalAlignment.Center;
                break;

            case TextVAlignment.Bottom:
                layout.VerticalAlignment = CanvasVerticalAlignment.Bottom;
                break;
            }

            _ds.DrawTextLayout(
                layout,
                new N.Vector2(
                    (float)rect.X,
                    (float)rect.Y),
                brush);

            layout.Dispose();
            format.Dispose();
        }
Ejemplo n.º 18
0
 public XTextWrapper(XText text) : base(text)
 {
 }
Ejemplo n.º 19
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="gfx"></param>
        /// <param name="text"></param>
        /// <param name="dx"></param>
        /// <param name="dy"></param>
        /// <param name="db"></param>
        /// <param name="r"></param>
        public void Draw(object gfx, XText text, double dx, double dy, ImmutableArray<ShapeProperty> db, Record r)
        {
            var _gfx = gfx as Graphics;

            var tbind = text.BindToTextProperty(db, r);
            if (string.IsNullOrEmpty(tbind))
                return;

            Brush brush = ToSolidBrush(text.Style.Stroke);

            var fontStyle = System.Drawing.FontStyle.Regular;
            if (text.Style.TextStyle.FontStyle.Flags.HasFlag(Kaliber3D.Render.FontStyleFlags.Bold))
            {
                fontStyle |= System.Drawing.FontStyle.Bold;
            }

            if (text.Style.TextStyle.FontStyle.Flags.HasFlag(Kaliber3D.Render.FontStyleFlags.Italic))
            {
                fontStyle |= System.Drawing.FontStyle.Italic;
            }

            if (text.Style.TextStyle.FontStyle.Flags.HasFlag(Kaliber3D.Render.FontStyleFlags.Underline))
            {
                fontStyle |= System.Drawing.FontStyle.Underline;
            }

            if (text.Style.TextStyle.FontStyle.Flags.HasFlag(Kaliber3D.Render.FontStyleFlags.Strikeout))
            {
                fontStyle |= System.Drawing.FontStyle.Strikeout;
            }

            Font font = new Font(
                text.Style.TextStyle.FontName,
                (float)(text.Style.TextStyle.FontSize * _textScaleFactor),
                fontStyle);

            var rect = CreateRect(
                text.TopLeft,
                text.BottomRight,
                dx, dy);

            var srect = new RectangleF(
                _scaleToPage(rect.X),
                _scaleToPage(rect.Y),
                _scaleToPage(rect.Width),
                _scaleToPage(rect.Height));

            var format = new StringFormat();
            switch (text.Style.TextStyle.TextHAlignment)
            {
                case TextHAlignment.Left:
                    format.Alignment = StringAlignment.Near;
                    break;
                case TextHAlignment.Center:
                    format.Alignment = StringAlignment.Center;
                    break;
                case TextHAlignment.Right:
                    format.Alignment = StringAlignment.Far;
                    break;
            }

            switch (text.Style.TextStyle.TextVAlignment)
            {
                case TextVAlignment.Top:
                    format.LineAlignment = StringAlignment.Near;
                    break;
                case TextVAlignment.Center:
                    format.LineAlignment = StringAlignment.Center;
                    break;
                case TextVAlignment.Bottom:
                    format.LineAlignment = StringAlignment.Far;
                    break;
            }

            format.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.NoClip;
            format.Trimming = StringTrimming.None;

            _gfx.DrawString(
                tbind,
                font,
                ToSolidBrush(text.Style.Stroke),
                srect,
                format);

            brush.Dispose();
            font.Dispose();
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Gets the X path.
        /// </summary>
        /// <param name="xobj">The xobj.</param>
        /// <returns>The x Path.</returns>
        public static string GetXPath(this XObject xobj)
        {
            if (xobj.Parent == null)
            {
                XDocument doc = xobj as XDocument;
                if (doc != null)
                {
                    return(".");
                }
                XElement el = xobj as XElement;
                if (el != null)
                {
                    return("/" + NameWithPredicate(el));
                }

                // the XPath data model does not include white space text nodes
                // that are children of a document, so this method returns null.
                XText xt = xobj as XText;
                if (xt != null)
                {
                    return(null);
                }
                XComment com = xobj as XComment;
                if (com?.Document != null)
                {
                    return("/" + (com.Document.Nodes().OfType <XComment>().Count() != 1 ? "comment()[" + (com.NodesBeforeSelf().OfType <XComment>().Count() + 1) + "]" : "comment()"));
                }
                XProcessingInstruction pi = xobj as XProcessingInstruction;
                if (pi?.Document != null)
                {
                    return("/" + (pi.Document.Nodes().OfType <XProcessingInstruction>().Count() != 1 ? "processing-instruction()[" + (pi.NodesBeforeSelf().OfType <XProcessingInstruction>().Count() + 1) + "]" : "processing-instruction()"));
                }
                return(null);
            }
            else
            {
                XElement el = xobj as XElement;
                if (el != null)
                {
                    return("/" + el.Ancestors().InDocumentOrder().Select(NameWithPredicate).StrCat("/") + NameWithPredicate(el));
                }

                XAttribute at = xobj as XAttribute;
                if (at?.Parent != null)
                {
                    return("/" + at.Parent.AncestorsAndSelf().InDocumentOrder().Select(NameWithPredicate).StrCat("/") + "@" + GetQName(at));
                }
                XComment com = xobj as XComment;
                if (com?.Parent != null)
                {
                    return("/" + com.Parent.AncestorsAndSelf().InDocumentOrder().Select(NameWithPredicate).StrCat("/") + (com.Parent.Nodes().OfType <XComment>().Count() != 1 ? "comment()[" + (com.NodesBeforeSelf().OfType <XComment>().Count() + 1) + "]" : "comment()"));
                }
                XCData cd = xobj as XCData;
                if (cd?.Parent != null)
                {
                    return("/" + cd.Parent.AncestorsAndSelf().InDocumentOrder().Select(NameWithPredicate).StrCat("/") + (cd.Parent.Nodes().OfType <XText>().Count() != 1 ? "text()[" + (cd.NodesBeforeSelf().OfType <XText>().Count() + 1) + "]" : "text()"));
                }
                XText tx = xobj as XText;
                if (tx?.Parent != null)
                {
                    return("/" + tx.Parent.AncestorsAndSelf().InDocumentOrder().Select(NameWithPredicate).StrCat("/") + (tx.Parent.Nodes().OfType <XText>().Count() != 1 ? "text()[" + (tx.NodesBeforeSelf().OfType <XText>().Count() + 1) + "]" : "text()"));
                }
                XProcessingInstruction pi = xobj as XProcessingInstruction;
                if (pi?.Parent != null)
                {
                    return("/" + pi.Parent.AncestorsAndSelf().InDocumentOrder().Select(NameWithPredicate).StrCat("/") + (pi.Parent.Nodes().OfType <XProcessingInstruction>().Count() != 1 ? "processing-instruction()[" + (pi.NodesBeforeSelf().OfType <XProcessingInstruction>().Count() + 1) + "]" : "processing-instruction()"));
                }
                return(null);
            }
        }
        public override bool WriteProjectFile(List <UnrealTargetPlatform> InPlatforms, List <UnrealTargetConfiguration> InConfigurations)
        {
            bool   bSuccess            = false;
            string ProjectNameRaw      = ProjectFilePath.GetFileNameWithoutExtension();
            string ProjectPath         = ProjectFilePath.FullName;
            string ProjectExtension    = ProjectFilePath.GetExtension();
            string ProjectPlatformName = BuildHostPlatform.Current.Platform.ToString();

            // Get the output directory
            string EngineRootDirectory = UnrealBuildTool.EngineDirectory.FullName;

            //
            // Build the working directory of the Game executable.
            //

            string GameWorkingDirectory = "";

            if (OnlyGameProject != null)
            {
                GameWorkingDirectory = Path.Combine(Path.GetDirectoryName(OnlyGameProject.FullName), "Binaries", ProjectPlatformName);
            }
            //
            // Build the working directory of the UE4Editor executable.
            //
            string UE4EditorWorkingDirectory = Path.Combine(EngineRootDirectory, "Binaries", ProjectPlatformName);

            //
            // Create the folder where the project files goes if it does not exist
            //
            String FilePath = Path.GetDirectoryName(ProjectFilePath.FullName);

            if ((FilePath.Length > 0) && !Directory.Exists(FilePath))
            {
                Directory.CreateDirectory(FilePath);
            }

            string GameProjectFile = "";

            if (OnlyGameProject != null)
            {
                GameProjectFile = OnlyGameProject.FullName;
            }

            //
            // Write all targets which will be separate projects.
            //
            foreach (ProjectTarget target in ProjectTargets)
            {
                string[] tmp = target.ToString().Split('.');
                string   ProjectTargetFileName = Path.GetDirectoryName(ProjectFilePath.FullName) + "/" + tmp [0] + ProjectExtension;
                String   TargetName            = tmp [0];
                var      ProjectTargetType     = target.TargetRules.Type;

                //
                // Create the CodeLites root element.
                //
                XElement   CodeLiteProject = new XElement("CodeLite_Project");
                XAttribute CodeLiteProjectAttributeName = new XAttribute("Name", TargetName);
                CodeLiteProject.Add(CodeLiteProjectAttributeName);

                //
                // Select only files we want to add.
                // TODO Maybe skipping those files directly in the following foreach loop is faster?
                //
                List <SourceFile> FilterSourceFile = SourceFiles.FindAll(s => (
                                                                             s.Reference.HasExtension(".h") ||
                                                                             s.Reference.HasExtension(".cpp") ||
                                                                             s.Reference.HasExtension(".c") ||
                                                                             s.Reference.HasExtension(".cs") ||
                                                                             s.Reference.HasExtension(".uproject") ||
                                                                             s.Reference.HasExtension(".uplugin") ||
                                                                             s.Reference.HasExtension(".ini") ||
                                                                             s.Reference.HasExtension(".usf") ||
                                                                             s.Reference.HasExtension(".ush")
                                                                             ));

                //
                // Find/Create the correct virtual folder and place the file into it.
                //
                foreach (var CurrentFile in FilterSourceFile)
                {
                    //
                    // Try to get the correct relative folder representation for the project.
                    //
                    String CurrentFilePath = "";
                    // TODO It seems that the full pathname doesn't work for some files like .ini, .usf, .ush
                    if ((ProjectTargetType == TargetType.Client) ||
                        (ProjectTargetType == TargetType.Editor) ||
                        (ProjectTargetType == TargetType.Game) ||
                        (ProjectTargetType == TargetType.Server))
                    {
                        if (TargetName.Equals("UE4Client") ||
                            TargetName.Equals("UE4Server") ||
                            TargetName.Equals("UE4Game") ||
                            TargetName.Equals("UE4Editor"))
                        {
                            int Idx = UnrealBuildTool.EngineDirectory.FullName.Length;
                            CurrentFilePath = Path.GetDirectoryName(Path.GetFullPath(CurrentFile.Reference.FullName)).Substring(Idx);
                        }
                        else
                        {
                            int Idx = Path.GetDirectoryName(CurrentFile.Reference.FullName).IndexOf(ProjectNameRaw) + ProjectNameRaw.Length;
                            CurrentFilePath = Path.GetDirectoryName(CurrentFile.Reference.FullName).Substring(Idx);
                        }
                    }
                    else if (ProjectTargetType == TargetType.Program)
                    {
                        //
                        // We do not need all the editors subfolders to show the content. Find the correct programs subfolder.
                        //
                        int Idx = Path.GetDirectoryName(CurrentFile.Reference.FullName).IndexOf(TargetName) + TargetName.Length;
                        CurrentFilePath = Path.GetDirectoryName(CurrentFile.Reference.FullName).Substring(Idx);
                    }

                    char[]    Delimiters   = new char[] { '/', '\\' };
                    string [] SplitFolders = CurrentFilePath.Split(Delimiters, StringSplitOptions.RemoveEmptyEntries);
                    //
                    // Set the CodeLite root folder again.
                    //
                    XElement root = CodeLiteProject;

                    //
                    // Iterate through all XElement virtual folders until we find the right place to put the file.
                    // TODO this looks more like a hack to me.
                    //
                    foreach (var FolderName in SplitFolders)
                    {
                        if (FolderName.Equals(""))
                        {
                            continue;
                        }

                        //
                        // Let's look if there is a virtual folder withint the current XElement.
                        //
                        IEnumerable <XElement> tests = root.Elements("VirtualDirectory");
                        if (IsEmpty(tests))
                        {
                            //
                            // No, then we have to create.
                            //
                            XElement   vf  = new XElement("VirtualDirectory");
                            XAttribute vfn = new XAttribute("Name", FolderName);
                            vf.Add(vfn);
                            root.Add(vf);
                            root = vf;
                        }
                        else
                        {
                            //
                            // Yes, then let's find the correct sub XElement.
                            //
                            bool notfound = true;

                            //
                            // We have some virtual directories let's find the correct one.
                            //
                            foreach (var element in tests)
                            {
                                //
                                // Look the the following folder
                                XAttribute attribute = element.Attribute("Name");
                                if (attribute.Value == FolderName)
                                {
                                    // Ok, we found the folder as subfolder, let's use it.
                                    root     = element;
                                    notfound = false;
                                    break;
                                }
                            }
                            //
                            // If we are here we didn't find any XElement with that subfolder, then we have to create.
                            //
                            if (notfound)
                            {
                                XElement   vf  = new XElement("VirtualDirectory");
                                XAttribute vfn = new XAttribute("Name", FolderName);
                                vf.Add(vfn);
                                root.Add(vf);
                                root = vf;
                            }
                        }
                    }

                    //
                    // If we are at this point we found the correct XElement folder
                    //
                    XElement   file          = new XElement("File");
                    XAttribute fileAttribute = new XAttribute("Name", CurrentFile.Reference.FullName);
                    file.Add(fileAttribute);
                    root.Add(file);
                }

                XElement CodeLiteSettings = new XElement("Settings");
                CodeLiteProject.Add(CodeLiteSettings);

                XElement CodeLiteGlobalSettings = new XElement("GlobalSettings");
                CodeLiteProject.Add(CodeLiteGlobalSettings);

                foreach (var CurConf in InConfigurations)
                {
                    XElement   CodeLiteConfiguration     = new XElement("Configuration");
                    XAttribute CodeLiteConfigurationName = new XAttribute("Name", CurConf.ToString());
                    CodeLiteConfiguration.Add(CodeLiteConfigurationName);

                    //
                    // Create Configuration General part.
                    //
                    XElement CodeLiteConfigurationGeneral = new XElement("General");

                    //
                    // Create the executable filename.
                    //
                    string ExecutableToRun       = "";
                    string PlatformConfiguration = "-" + ProjectPlatformName + "-" + CurConf.ToString();
                    switch (BuildHostPlatform.Current.Platform)
                    {
                    case UnrealTargetPlatform.Linux:
                    {
                        ExecutableToRun = "./" + TargetName;
                        if ((ProjectTargetType == TargetType.Game) ||
                            (ProjectTargetType == TargetType.Program))
                        {
                            if (CurConf != UnrealTargetConfiguration.Development)
                            {
                                ExecutableToRun += PlatformConfiguration;
                            }
                        }
                        else if (ProjectTargetType == TargetType.Editor)
                        {
                            ExecutableToRun = "./UE4Editor";
                            if ((CurConf == UnrealTargetConfiguration.Debug) ||
                                (CurConf == UnrealTargetConfiguration.Shipping) ||
                                (CurConf == UnrealTargetConfiguration.Test))
                            {
                                ExecutableToRun += PlatformConfiguration;
                            }
                        }
                    }
                    break;

                    case UnrealTargetPlatform.Mac:
                    {
                        ExecutableToRun = "./" + TargetName;
                        if ((ProjectTargetType == TargetType.Game) || (ProjectTargetType == TargetType.Program))
                        {
                            if (CurConf != UnrealTargetConfiguration.Development)
                            {
                                ExecutableToRun += PlatformConfiguration;
                            }
                            ExecutableToRun += ".app/Contents/MacOS/" + TargetName;
                            if (CurConf != UnrealTargetConfiguration.Development)
                            {
                                ExecutableToRun += PlatformConfiguration;
                            }
                        }
                        else if (ProjectTargetType == TargetType.Editor)
                        {
                            ExecutableToRun = "./UE4Editor";
                            if ((CurConf == UnrealTargetConfiguration.Debug) ||
                                (CurConf == UnrealTargetConfiguration.Shipping) ||
                                (CurConf == UnrealTargetConfiguration.Test))
                            {
                                ExecutableToRun += PlatformConfiguration;
                            }
                            ExecutableToRun += ".app/Contents/MacOS/UE4Editor";
                            if ((CurConf != UnrealTargetConfiguration.Development) && (CurConf != UnrealTargetConfiguration.DebugGame))
                            {
                                ExecutableToRun += PlatformConfiguration;
                            }
                        }
                    }
                    break;

                    case UnrealTargetPlatform.Win64:
                    case UnrealTargetPlatform.Win32:
                    {
                        ExecutableToRun = TargetName;
                        if ((ProjectTargetType == TargetType.Game) || (ProjectTargetType == TargetType.Program))
                        {
                            if (CurConf != UnrealTargetConfiguration.Development)
                            {
                                ExecutableToRun += PlatformConfiguration;
                            }
                        }
                        else if (ProjectTargetType == TargetType.Editor)
                        {
                            ExecutableToRun = "UE4Editor";
                            if ((CurConf == UnrealTargetConfiguration.Debug) ||
                                (CurConf == UnrealTargetConfiguration.Shipping) ||
                                (CurConf == UnrealTargetConfiguration.Test))
                            {
                                ExecutableToRun += PlatformConfiguration;
                            }
                        }

                        ExecutableToRun += ".exe";
                    }
                    break;

                    default:
                        throw new BuildException("Unsupported platform.");
                    }


                    // Is this project a Game type?
                    XAttribute GeneralExecutableToRun = new XAttribute("Command", ExecutableToRun);
                    if (ProjectTargetType == TargetType.Game)
                    {
                        if (CurConf.ToString().Contains("Debug"))
                        {
                            string     commandArguments = " -debug";
                            XAttribute GeneralExecutableToRunArguments = new XAttribute("CommandArguments", commandArguments);
                            CodeLiteConfigurationGeneral.Add(GeneralExecutableToRunArguments);
                        }
                        if (TargetName.Equals("UE4Game"))
                        {
                            XAttribute GeneralExecutableWorkingDirectory = new XAttribute("WorkingDirectory", UE4EditorWorkingDirectory);
                            CodeLiteConfigurationGeneral.Add(GeneralExecutableWorkingDirectory);
                        }
                        else
                        {
                            XAttribute GeneralExecutableWorkingDirectory = new XAttribute("WorkingDirectory", GameWorkingDirectory);
                            CodeLiteConfigurationGeneral.Add(GeneralExecutableWorkingDirectory);
                        }
                    }
                    else if (ProjectTargetType == TargetType.Editor)
                    {
                        if (TargetName != "UE4Editor" && GameProjectFile != "")
                        {
                            string commandArguments = "\"" + GameProjectFile + "\"" + " -game";
                            if (CurConf.ToString().Contains("Debug"))
                            {
                                commandArguments += " -debug";
                            }
                            XAttribute CommandArguments = new XAttribute("CommandArguments", commandArguments);
                            CodeLiteConfigurationGeneral.Add(CommandArguments);
                        }
                        XAttribute WorkingDirectory = new XAttribute("WorkingDirectory", UE4EditorWorkingDirectory);
                        CodeLiteConfigurationGeneral.Add(WorkingDirectory);
                    }
                    else if (ProjectTargetType == TargetType.Program)
                    {
                        XAttribute WorkingDirectory = new XAttribute("WorkingDirectory", UE4EditorWorkingDirectory);
                        CodeLiteConfigurationGeneral.Add(WorkingDirectory);
                    }
                    else if (ProjectTargetType == TargetType.Client)
                    {
                        XAttribute WorkingDirectory = new XAttribute("WorkingDirectory", UE4EditorWorkingDirectory);
                        CodeLiteConfigurationGeneral.Add(WorkingDirectory);
                    }
                    else if (ProjectTargetType == TargetType.Server)
                    {
                        XAttribute WorkingDirectory = new XAttribute("WorkingDirectory", UE4EditorWorkingDirectory);
                        CodeLiteConfigurationGeneral.Add(WorkingDirectory);
                    }
                    CodeLiteConfigurationGeneral.Add(GeneralExecutableToRun);

                    CodeLiteConfiguration.Add(CodeLiteConfigurationGeneral);

                    //
                    // End of Create Configuration General part.
                    //

                    //
                    // Create Configuration Custom Build part.
                    //
                    XElement CodeLiteConfigurationCustomBuild = new XElement("CustomBuild");
                    CodeLiteConfiguration.Add(CodeLiteConfigurationGeneral);
                    XAttribute CodeLiteConfigurationCustomBuildEnabled = new XAttribute("Enabled", "yes");
                    CodeLiteConfigurationCustomBuild.Add(CodeLiteConfigurationCustomBuildEnabled);

                    //
                    // Add the working directory for the custom build commands.
                    //
                    XElement CustomBuildWorkingDirectory  = new XElement("WorkingDirectory");
                    XText    CustuomBuildWorkingDirectory = new XText(Path.GetDirectoryName(UnrealBuildTool.GetUBTPath()));
                    CustomBuildWorkingDirectory.Add(CustuomBuildWorkingDirectory);
                    CodeLiteConfigurationCustomBuild.Add(CustomBuildWorkingDirectory);

                    //
                    // End of Add the working directory for the custom build commands.
                    //



                    //
                    // Make Build Target.
                    //
                    XElement CustomBuildCommand = new XElement("BuildCommand");
                    CodeLiteConfigurationCustomBuild.Add(CustomBuildCommand);

                    string BuildTarget = Path.GetFileName(UnrealBuildTool.GetUBTPath()) + " " + TargetName + " " + ProjectPlatformName + " " + CurConf.ToString();
                    if ((BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Win64) &&
                        (BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Win32))
                    {
                        BuildTarget = "mono " + BuildTarget;
                    }

                    if (GameProjectFile.Length > 0)
                    {
                        BuildTarget += " -project=" + "\"" + GameProjectFile + "\"";
                    }

                    XText commandLine = new XText(BuildTarget);
                    CustomBuildCommand.Add(commandLine);

                    //
                    // End of Make Build Target
                    //

                    //
                    // Clean Build Target.
                    //
                    XElement CustomCleanCommand = new XElement("CleanCommand");
                    CodeLiteConfigurationCustomBuild.Add(CustomCleanCommand);

                    string CleanTarget      = BuildTarget + " -clean";
                    XText  CleanCommandLine = new XText(CleanTarget);

                    CustomCleanCommand.Add(CleanCommandLine);


                    //
                    // End of Clean Build Target.
                    //

                    //
                    // Rebuild Build Target.
                    //
                    XElement CustomRebuildCommand = new XElement("RebuildCommand");
                    CodeLiteConfigurationCustomBuild.Add(CustomRebuildCommand);

                    string RebuildTarget      = CleanTarget + "\n" + BuildTarget;
                    XText  RebuildCommandLine = new XText(RebuildTarget);

                    CustomRebuildCommand.Add(RebuildCommandLine);

                    //
                    // End of Clean Build Target.
                    //


                    //
                    // Some other fun Custom Targets.
                    //
                    if (ProjectTargetType == TargetType.Game)
                    {
                        string CookGameCommandLine = "mono AutomationTool.exe BuildCookRun ";

                        // Projects filename
                        if (OnlyGameProject != null)
                        {
                            CookGameCommandLine += "-project=\"" + OnlyGameProject.FullName + "\" ";
                        }

                        // Disables Perforce functionality
                        CookGameCommandLine += "-noP4 ";

                        // Do not kill any spawned processes on exit
                        CookGameCommandLine += "-nokill ";
                        CookGameCommandLine += "-clientconfig=" + CurConf.ToString() + " ";
                        CookGameCommandLine += "-serverconfig=" + CurConf.ToString() + " ";
                        CookGameCommandLine += "-platform=" + ProjectPlatformName + " ";
                        CookGameCommandLine += "-targetplatform=" + ProjectPlatformName + " ";                                 // TODO Maybe I can add all the supported one.
                        CookGameCommandLine += "-nocompile ";
                        CookGameCommandLine += "-compressed -stage -deploy";

                        //
                        // Cook Game.
                        //
                        XElement   CookGame        = new XElement("Target");
                        XAttribute CookGameName    = new XAttribute("Name", "Cook Game");
                        XText      CookGameCommand = new XText(CookGameCommandLine + " -cook");
                        CookGame.Add(CookGameName);
                        CookGame.Add(CookGameCommand);
                        CodeLiteConfigurationCustomBuild.Add(CookGame);

                        XElement   CookGameOnTheFly         = new XElement("Target");
                        XAttribute CookGameNameOnTheFlyName = new XAttribute("Name", "Cook Game on the fly");
                        XText      CookGameOnTheFlyCommand  = new XText(CookGameCommandLine + " -cookonthefly");
                        CookGameOnTheFly.Add(CookGameNameOnTheFlyName);
                        CookGameOnTheFly.Add(CookGameOnTheFlyCommand);
                        CodeLiteConfigurationCustomBuild.Add(CookGameOnTheFly);

                        XElement   SkipCook        = new XElement("Target");
                        XAttribute SkipCookName    = new XAttribute("Name", "Skip Cook Game");
                        XText      SkipCookCommand = new XText(CookGameCommandLine + " -skipcook");
                        SkipCook.Add(SkipCookName);
                        SkipCook.Add(SkipCookCommand);
                        CodeLiteConfigurationCustomBuild.Add(SkipCook);
                    }
                    //
                    // End of Some other fun Custom Targets.
                    //
                    CodeLiteConfiguration.Add(CodeLiteConfigurationCustomBuild);

                    //
                    // End of Create Configuration Custom Build part.
                    //

                    CodeLiteSettings.Add(CodeLiteConfiguration);
                }

                CodeLiteSettings.Add(CodeLiteGlobalSettings);

                //
                // Save the XML file.
                //
                CodeLiteProject.Save(ProjectTargetFileName);

                bSuccess = true;
            }
            return(bSuccess);
        }
Ejemplo n.º 22
0
        private static bool TextPartsMatch(string firstText, string secondText, XText firstTextPart, XText secondTextPart)
        {
            string firstTextPartText = firstTextPart.Value.TrimStart();

            if (!string.Equals(firstText, firstTextPartText, StringComparison.Ordinal))
            {
                return(false);
            }

            string secondTextPartText = secondTextPart.Value;

            return(secondTextPartText.StartsWith(secondText, StringComparison.Ordinal));
        }
Ejemplo n.º 23
0
        private void CompileSingle(XNode node, Font font, bool bold, bool italic, bool underline, List <List <ContentBlock> > lines, ref List <ContentBlock> current)
        {
            XElement element = node as XElement;
            XText    text    = node as XText;

            if (element != null)
            {
                switch (element.Name.LocalName)
                {
                case "content":
                    foreach (var n in element.Nodes())
                    {
                        CompileSingle(n, font, bold, italic, underline, lines, ref current);
                    }
                    break;

                case "b":
                    foreach (var n in element.Nodes())
                    {
                        CompileSingle(n, font, true, italic, underline, lines, ref current);
                    }
                    break;

                case "i":
                    foreach (var n in element.Nodes())
                    {
                        CompileSingle(n, font, bold, true, underline, lines, ref current);
                    }
                    break;

                case "u":
                    foreach (var n in element.Nodes())
                    {
                        CompileSingle(n, font, bold, italic, true, lines, ref current);
                    }
                    break;
                }
            }
            else
            {
                string[] textLines = text.Value
                                     .Split(new string[] { "\r\n" }, StringSplitOptions.None)
                                     .SelectMany(s => s.Split(new string[] { "\r", "\n" }, StringSplitOptions.None))
                                     .Select(s => string.IsNullOrEmpty(s) ? " " : s)
                                     .ToArray();
                for (int i = 0; i < textLines.Length; i++)
                {
                    if (i > 0)
                    {
                        current = new List <ContentBlock>();
                        lines.Add(current);
                    }
                    TextBlock block = new TextBlock()
                    {
                        FontSkeleton = font,
                        Bold         = bold,
                        Italic       = italic,
                        Underline    = underline,
                        Color        = Color.Black,
                        Text         = textLines[i]
                    };
                    current.Add(block);
                }
            }
        }
Ejemplo n.º 24
0
        static void Main(string[] args)
        {
            InitOpenOfficeEnvironment();
            XMultiServiceFactory multiServiceFactory = Connect();
            XComponent           xComponent          = null;

            string docFileName = @"C:\test3.doc";

            try
            {
                XComponentLoader componentLoader =
                    (XComponentLoader)multiServiceFactory
                    .createInstance("com.sun.star.frame.Desktop");
                //set the property
                PropertyValue[] propertyValue = new PropertyValue[1];
                PropertyValue   aProperty     = new PropertyValue();
                aProperty.Name   = "Hidden";
                aProperty.Value  = new uno.Any(false);
                propertyValue[0] = aProperty;
                xComponent       =
                    componentLoader
                    .loadComponentFromURL(PathConverter(docFileName),
                                          "_blank", 0, propertyValue);
                XTextDocument      xTextDocument      = ((XTextDocument)xComponent);
                XEnumerationAccess xEnumerationAccess =
                    (XEnumerationAccess)xTextDocument.getText();
                XEnumeration xParagraphEnumeration =
                    xEnumerationAccess.createEnumeration();
                while (xParagraphEnumeration.hasMoreElements())
                {
                    uno.Any      element = xParagraphEnumeration.nextElement();
                    XServiceInfo xinfo   = (XServiceInfo)element.Value;
                    if (xinfo.supportsService("com.sun.star.text.TextTable"))
                    {
                        Console.WriteLine("Found Table!");

                        XTextTable xTextTable = (XTextTable)element.Value;
                        String[]   cellNames  = xTextTable.getCellNames();

                        for (int i = 0; i < cellNames.Length; i++)
                        {
                            XCell  xCell     = xTextTable.getCellByName(cellNames[i]);
                            XText  xTextCell = (XText)xCell;
                            String strText   = xTextCell.getString();
                            Console.WriteLine(strText);
                        }
                    }
                    else
                    {
                        XTextContent       xTextElement           = (XTextContent)element.Value;
                        XEnumerationAccess xParaEnumerationAccess =
                            (XEnumerationAccess)xTextElement;
                        // create another enumeration to get all text portions of
                        //the paragraph
                        XEnumeration xTextPortionEnum =
                            xParaEnumerationAccess.createEnumeration();
                        //step 3  Through the Text portions Enumeration, get interface
                        //to each individual text portion
                        while (xTextPortionEnum.hasMoreElements())
                        {
                            XTextRange xTextPortion =
                                (XTextRange)xTextPortionEnum.nextElement().Value;
                            Console.Write(xTextPortion.getString());
                        }
                    }
                }
            }
            catch (unoidl.com.sun.star.uno.Exception exp1)
            {
                Console.WriteLine(exp1.Message);
                Console.WriteLine(exp1.StackTrace);
            }
            catch (System.Exception exp2)
            {
                Console.WriteLine(exp2.Message);
                Console.WriteLine(exp2.StackTrace);
            }
            finally
            {
                xComponent.dispose();
                xComponent = null;
            }
            Console.WriteLine("Done.");
            Console.ReadLine();
        }
Ejemplo n.º 25
0
 public XRaw(XText text) : base(text)
 {
 }
Ejemplo n.º 26
0
        public void Load(XNode xText)
        {
            subtext.Clear();
            if (xText == null)
            {
                throw new ArgumentNullException("xText");
            }
            switch (xText.NodeType)
            {
            case XmlNodeType.Text:
                XText textNode = (XText)xText;
                if (!string.IsNullOrEmpty(textNode.Value))
                {
                    Text  = textNode.Value;
                    style = TextStyles.Normal;
                }
                break;

            case XmlNodeType.Element:
                XElement xTextElement = (XElement)xText;
                if (xTextElement.HasElements)
                {
                    Text  = string.Empty;
                    style = GetStyle(xTextElement.Name.LocalName);
                    IEnumerable <XNode> childElements = xTextElement.Nodes();
                    foreach (var node in childElements)
                    {
                        if (node.NodeType == XmlNodeType.Element)
                        {
                            XElement element = (XElement)node;
                            switch (element.Name.LocalName)
                            {
                            case InternalLinkItem.Fb2InternalLinkElementName:
                                InternalLinkItem link = new InternalLinkItem();
                                try
                                {
                                    link.Load(element);
                                    subtext.Add(link);
                                }
                                catch (Exception)
                                {
                                    continue;
                                }
                                break;

                            case InlineImageItem.Fb2InlineImageElementName:
                                InlineImageItem image = new InlineImageItem();
                                try
                                {
                                    image.Load(element);
                                    subtext.Add(image);
                                }
                                catch (Exception)
                                {
                                    continue;
                                }
                                break;

                            default:
                                SimpleText text = new SimpleText();
                                try
                                {
                                    text.Load(element);
                                    subtext.Add(text);
                                }
                                catch (Exception)
                                {
                                    continue;
                                }
                                break;
                            }
                        }
                        else
                        {
                            SimpleText text = new SimpleText();
                            try
                            {
                                text.Load(node);
                                subtext.Add(text);
                            }
                            catch (Exception)
                            {
                                continue;
                            }
                        }
                    }
                }
                else
                {
                    style = GetStyle(xTextElement.Name.LocalName);
                    Text  = xTextElement.Value;
                    //switch (xTextElement.Name.LocalName)
                    //{
                    //    case "strong":
                    //        Text = xTextElement.Value;
                    //        break;
                    //    case "emphasis":
                    //        Text = xTextElement.Value;
                    //        break;
                    //    case "code":
                    //        Text = xTextElement.Value;
                    //        break;
                    //    case "sub":
                    //        Text = xTextElement.Value;
                    //        break;
                    //    case "sup":
                    //        Text = xTextElement.Value;
                    //        break;
                    //    case "strikethrough":
                    //        Text = xTextElement.Value;
                    //        break;
                    //    default:
                    //        Text = xTextElement.Value;
                    //        break;
                    //}
                }
                break;
            }
        }
Ejemplo n.º 27
0
 public static bool ParseBool(this XText e, bool def = false)
 {
     return(ParseBool(e == null ? null : e.Value, def));
 }
Ejemplo n.º 28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SimpleText"/> class.
 /// </summary>
 /// <param name="document">The document.</param>
 /// <param name="simpleText">The simple text.</param>
 public SimpleText(IDocument document, string simpleText)
 {
     Document = document;
     Node     = new XText(simpleText ?? string.Empty);
 }
Ejemplo n.º 29
0
 public static DateTime ParseDateTime(this XText e, string format)
 {
     return(ParseDateTime(e == null ? null : e.Value, format));
 }
Ejemplo n.º 30
0
        public static void AddFileToProject(string projectFile, string codeFile, string dependentUpon = null)
        {
            if (File.Exists(projectFile))
            {
                XElement doc;
                using (var sr = new StreamReader(projectFile))
                    doc = XElement.Parse(sr.ReadToEnd(), LoadOptions.PreserveWhitespace | LoadOptions.SetLineInfo);

                var ns = doc.GetDefaultNamespace();

                Func <string, XElement> findItemGroupOf = fileName =>
                {
                    foreach (var group in doc.Elements(ns + "ItemGroup"))
                    {
                        foreach (var c in group.Elements(ns + "Compile")
                                 .Concat(group.Elements(ns + "TypeScriptCompile"))
                                 .Concat(group.Elements(ns + "Content"))
                                 .Concat(group.Elements(ns + "None")))
                        {
                            if (c.Attribute("Include").Value.ToLowerInvariant() == fileName.ToLowerInvariant())
                            {
                                return(group);
                            }
                        }
                    }

                    return(null);
                };

                if (findItemGroupOf(codeFile) != null)
                {
                    return;
                }

                XElement dependentGroup = null;
                if (dependentUpon != null)
                {
                    dependentGroup = findItemGroupOf(dependentUpon);
                    if (dependentGroup == null)
                    {
                        dependentUpon = null;
                    }
                }

                string contentType;
                if (String.Compare(Path.GetExtension(codeFile), ".cs") == 0)
                {
                    contentType = "Compile";
                }
                else if (String.Compare(Path.GetExtension(codeFile), ".ts") == 0)
                {
                    contentType = "TypeScriptCompile";
                }
                else
                {
                    contentType = "Content";
                }

                XElement targetGroup = dependentGroup;
                if (targetGroup == null)
                {
                    foreach (var group in doc.Elements(ns + "ItemGroup"))
                    {
                        var compiles = group.Elements(ns + contentType);
                        if (compiles.Count() > 0)
                        {
                            targetGroup = group;
                            break;
                        }
                    }
                }

                if (targetGroup == null)
                {
                    return; // create a group??
                }
                var newElement = new XElement(ns + contentType, new XAttribute("Include", codeFile));

                var   lastElement = targetGroup.Elements().LastOrDefault();
                XText space       = null;
                if (lastElement != null)
                {
                    space = lastElement.PreviousNode as XText;
                }
                if (lastElement != null)
                {
                    if (space != null)
                    {
                        lastElement.AddAfterSelf(new XText(space.Value), newElement);
                    }
                    else
                    {
                        lastElement.AddAfterSelf(newElement);
                    }
                }
                else
                {
                    targetGroup.Add(newElement);
                }

                if (dependentUpon != null)
                {
                    newElement.Add(new XText("  "));
                    newElement.Add(new XElement(ns + "DependentUpon", Path.GetFileName(dependentUpon)));
                }

                using (var ms = new MemoryStream())
                    using (var sw = new StreamWriter(ms, new UTF8Encoding(true)))
                    {
                        sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                        sw.Write(doc.ToString());
                        sw.Flush();
                        var bytes = ms.ToArray();
                        CodeFileHelper.CheckoutAndWrite(projectFile, bytes, false);
                    }
            }
        }
Ejemplo n.º 31
0
 public static TimeSpan ParseUtcOffset(this XText e)
 {
     return(ParseUtcOffset(e == null ? null : e.Value));
 }
        private void setXmlValue(XDocument xmlDoc, string scope, SettingsPropertyValue value)
        {
            if (!IsUserScoped(value.Property))
            {
                return;
            }
            //determine the location of the settings property
            XElement xmlSettings = xmlDoc.Element("configuration").Element("userSettings");
            XElement xmlSettingsLoc;

            if (IsRoaming(value.Property))
            {
                xmlSettingsLoc = xmlSettings.Element("Roaming");
            }
            else
            {
                xmlSettingsLoc = xmlSettings.Element("PC_" + Environment.MachineName);
            }
            // the serialized value to be saved
            XNode serialized;

            if (value.SerializedValue == null)
            {
                serialized = new XText("");
            }
            else if (value.Property.SerializeAs == SettingsSerializeAs.Xml)
            {
                serialized = XElement.Parse((string)value.SerializedValue);
            }
            else if (value.Property.SerializeAs == SettingsSerializeAs.Binary)
            {
                serialized = new XText(Convert.ToBase64String((byte[])value.SerializedValue));
            }
            else
            {
                serialized = new XText((string)value.SerializedValue);
            }
            // check if setting already exists, otherwise create new
            if (xmlSettingsLoc == null)
            {
                if (IsRoaming(value.Property))
                {
                    xmlSettingsLoc = new XElement("Roaming");
                }
                else
                {
                    xmlSettingsLoc = new XElement("PC_" + Environment.MachineName);
                }
                xmlSettingsLoc.Add(new XElement(scope,
                                                new XElement(value.Name, serialized)));
                xmlSettings.Add(xmlSettingsLoc);
            }
            else
            {
                XElement xmlScope = xmlSettingsLoc.Element(scope);
                if (xmlScope != null)
                {
                    XElement xmlElem = xmlScope.Element(value.Name);
                    if (xmlElem == null)
                    {
                        xmlScope.Add(new XElement(value.Name, serialized));
                    }
                    else
                    {
                        xmlElem.ReplaceAll(serialized);
                    }
                }
                else
                {
                    xmlSettingsLoc.Add(new XElement(scope, new XElement(value.Name, serialized)));
                }
            }
        }
Ejemplo n.º 33
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dc"></param>
        /// <param name="text"></param>
        /// <param name="dx"></param>
        /// <param name="dy"></param>
        /// <param name="db"></param>
        /// <param name="r"></param>
        public void Draw(object dc, XText text, double dx, double dy, ImmutableArray<ShapeProperty> db, Record r)
        {
            var _dc = dc as DrawingContext;

            var style = text.Style;
            if (style == null)
                return;

            var tbind = text.BindToTextProperty(db, r);
            if (string.IsNullOrEmpty(tbind))
                return;

            double thickness = style.Thickness / _state.Zoom;
            double half = thickness / 2.0;

            Tuple<Brush, Pen> cache = null;
            Brush fill;
            Pen stroke;
            if (_enableStyleCache
                && _styleCache.TryGetValue(style, out cache))
            {
                fill = cache.Item1;
                stroke = cache.Item2;
            }
            else
            {
                fill = CreateBrush(style.Fill);
                stroke = CreatePen(style, thickness);
                if (_enableStyleCache)
                    _styleCache.Add(style, Tuple.Create(fill, stroke));
            }

            var rect = CreateRect(
                text.TopLeft,
                text.BottomRight,
                dx, dy);

            Tuple<string, FormattedText, ShapeStyle> tcache = null;
            FormattedText ft;
            string ct;
            if (_enableTextCache
                && _textCache.TryGetValue(text, out tcache)
                && string.Compare(tcache.Item1, tbind) == 0
                && tcache.Item3 == style)
            {
                ct = tcache.Item1;
                ft = tcache.Item2;

                _dc.DrawText(
                    ft,
                    GetTextOrigin(style, ref rect, ft));
            }
            else
            {
                var ci = CultureInfo.InvariantCulture;

                var fontStyle = System.Windows.FontStyles.Normal;
                if (style.TextStyle.FontStyle.Flags.HasFlag(Kaliber3D.Render.FontStyleFlags.Italic))
                {
                    fontStyle = System.Windows.FontStyles.Italic;
                }

                var fontWeight = FontWeights.Regular;
                if (style.TextStyle.FontStyle.Flags.HasFlag(Kaliber3D.Render.FontStyleFlags.Bold))
                {
                    fontWeight = FontWeights.Bold;
                }

                var tf = new Typeface(
                    new FontFamily(style.TextStyle.FontName),
                    fontStyle,
                    fontWeight,
                    FontStretches.Normal);

                ft = new FormattedText(
                    tbind,
                    ci,
                    ci.TextInfo.IsRightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight,
                    tf,
                    style.TextStyle.FontSize > 0.0 ? style.TextStyle.FontSize : double.Epsilon,
                    stroke.Brush, null, TextFormattingMode.Ideal);

                if (style.TextStyle.FontStyle.Flags.HasFlag(Kaliber3D.Render.FontStyleFlags.Underline)
                    || style.TextStyle.FontStyle.Flags.HasFlag(Kaliber3D.Render.FontStyleFlags.Strikeout))
                {
                    var decorations = new TextDecorationCollection();

                    if (style.TextStyle.FontStyle.Flags.HasFlag(Kaliber3D.Render.FontStyleFlags.Underline))
                    {
                        decorations = new TextDecorationCollection(
                            decorations.Union(TextDecorations.Underline));
                    }

                    if (style.TextStyle.FontStyle.Flags.HasFlag(Kaliber3D.Render.FontStyleFlags.Strikeout))
                    {
                        decorations = new TextDecorationCollection(
                            decorations.Union(TextDecorations.Strikethrough));
                    }

                    ft.SetTextDecorations(decorations);
                }

                if (_enableTextCache)
                {
                    var tuple = Tuple.Create(tbind, ft, style);
                    if (_textCache.ContainsKey(text))
                    {
                        _textCache[text] = tuple;
                    }
                    else
                    {
                        _textCache.Add(text, tuple);
                    }
                }

                _dc.DrawText(
                    ft,
                    GetTextOrigin(style, ref rect, ft));
            }
        }
Ejemplo n.º 34
0
 public IText CreateText()
 {
     var text = new XText()
     {
         Point1 = new XPoint(0.0, 0.0),
         Point2 = new XPoint(0.0, 0.0),
         HorizontalAlignment = 1,
         VerticalAlignment = 1,
         Size = 11.0,
         Text = "Text",
         Foreground = new XColor(0xFF, 0x00, 0x00, 0x00),
         Backgroud = new XColor(0x00, 0xFF, 0xFF, 0xFF),
     };
     text.Point1.Connected.Add(text);
     text.Point2.Connected.Add(text);
     return text;
 }
Ejemplo n.º 35
0
        public void TextWholeVsConcatenate()
        {
            XElement e = new XElement("A", new XText("_start_"), new XText("_end_"));
            XNode[] pieces = new XNode[] { new XText("_start_"), new XText("_end_") };
            XText together = new XText("_start__end_");

            VerifyComparison(true, e.FirstNode, pieces[0]);
            VerifyComparison(true, e.LastNode, pieces[1]);
            VerifyComparison(false, e.FirstNode, together);
            VerifyComparison(false, e.LastNode, together);
        }
Ejemplo n.º 36
0
        public void Inherits_From_BaseShape()
        {
            var target = new XText();

            Assert.True(target is BaseShape);
        }
Ejemplo n.º 37
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="text"></param>
 /// <param name="x"></param>
 /// <param name="y"></param>
 public void TryToConnectTopLeft(XText text, double x, double y)
 {
     var result = ShapeBounds.HitTest(_editor.Project.CurrentContainer, new Vector2(x, y), _editor.Project.Options.HitTreshold);
     if (result != null && result is XPoint)
     {
         text.TopLeft = result as XPoint;
     }
 }
Ejemplo n.º 38
0
        protected bool ProcessCell(ICell cell, XElement tableCellElement,
                                   int normalWidthPx, int maxSpannedWidthPx, float normalHeightPt)
        {
            ICellStyle cellStyle = cell.CellStyle as ICellStyle;

            string value;

            switch (cell.CellType)
            {
            case CellType.String:
                // XXX: enrich
                value = cell.RichStringCellValue.String;
                break;

            case CellType.Formula:
                switch (cell.CachedFormulaResultType)
                {
                case CellType.String:
                    IRichTextString str = cell.RichStringCellValue;
                    if (str != null && str.Length > 0)
                    {
                        value = (str.String);
                    }
                    else
                    {
                        value = string.Empty;
                    }
                    break;

                case CellType.Numeric:
                    ICellStyle style = cellStyle;
                    if (style == null)
                    {
                        value = cell.NumericCellValue.ToString();
                    }
                    else
                    {
                        value = (_formatter.FormatRawCellContents(cell.NumericCellValue, style.DataFormat, style.GetDataFormatString()));
                    }
                    break;

                case CellType.Boolean:
                    value = cell.BooleanCellValue.ToString();
                    break;

                case CellType.Error:
                    value = ErrorEval.GetText(cell.ErrorCellValue);
                    break;

                default:
                    logger.Log(POILogger.WARN, "Unexpected cell cachedFormulaResultType (" + cell.CachedFormulaResultType.ToString() + ")");
                    value = string.Empty;
                    break;
                }
                break;

            case CellType.Blank:
                value = string.Empty;
                break;

            case CellType.Numeric:
                value = _formatter.FormatCellValue(cell);
                break;

            case CellType.Boolean:
                value = cell.BooleanCellValue.ToString();
                break;

            case CellType.Error:
                value = ErrorEval.GetText(cell.ErrorCellValue);
                break;

            default:
                logger.Log(POILogger.WARN, "Unexpected cell type (" + cell.CellType.ToString() + ")");
                return(true);
            }

            bool noText     = string.IsNullOrEmpty(value);
            bool wrapInDivs = !noText && UseDivsToSpan && !cellStyle.WrapText;

            short cellStyleIndex = cellStyle.Index;

            if (cellStyleIndex != 0)
            {
                IWorkbook workbook     = cell.Row.Sheet.Workbook as IWorkbook;
                string    mainCssClass = GetStyleClassName(workbook, cellStyle);
                if (wrapInDivs)
                {
                    tableCellElement.SetAttributeValue("class", mainCssClass + " "
                                                       + cssClassContainerCell);
                }
                else
                {
                    tableCellElement.SetAttributeValue("class", mainCssClass);
                }

                if (noText)
                {
                    /*
                     * if cell style is defined (like borders, etc.) but cell text
                     * is empty, add "&nbsp;" to output, so browser won't collapse
                     * and ignore cell
                     */
                    value = "\u00A0"; //“ ”全角空格
                }
            }

            if (OutputLeadingSpacesAsNonBreaking && value.StartsWith(" "))
            {
                StringBuilder builder = new StringBuilder();
                for (int c = 0; c < value.Length; c++)
                {
                    if (value[c] != ' ')
                    {
                        break;
                    }
                    builder.Append('\u00a0');
                }

                if (value.Length != builder.Length)
                {
                    builder.Append(value.Substring(builder.Length));
                }

                value = builder.ToString();
            }

            XText text = htmlDocumentFacade.CreateText(value);

            if (wrapInDivs)
            {
                XElement outerDiv = htmlDocumentFacade.CreateBlock();
                outerDiv.SetAttributeValue("class", this.cssClassContainerDiv);

                XElement      innerDiv      = htmlDocumentFacade.CreateBlock();
                StringBuilder innerDivStyle = new StringBuilder();
                innerDivStyle.Append("position:absolute;min-width:");
                innerDivStyle.Append(normalWidthPx);
                innerDivStyle.Append("px;");
                if (maxSpannedWidthPx != int.MaxValue)
                {
                    innerDivStyle.Append("max-width:");
                    innerDivStyle.Append(maxSpannedWidthPx);
                    innerDivStyle.Append("px;");
                }
                innerDivStyle.Append("overflow:hidden;max-height:");
                innerDivStyle.Append(normalHeightPt);
                innerDivStyle.Append("pt;white-space:nowrap;");
                ExcelToHtmlUtils.AppendAlign(innerDivStyle, cellStyle.Alignment);
                htmlDocumentFacade.AddStyleClass(outerDiv, "d", innerDivStyle.ToString());

                innerDiv.AppendChild(text);
                outerDiv.AppendChild(innerDiv);
                tableCellElement.AppendChild(outerDiv);
            }
            else
            {
                tableCellElement.AppendChild(text);
            }

            return(string.IsNullOrEmpty(value) && cellStyleIndex == 0);
        }
 public static void SetOldValue(XText oldText)
 {
     currentParent = oldText.Parent;
     currentOldValue = oldText.Value;
 }
Ejemplo n.º 40
0
        /// <summary>
        /// Initializes static designer context.
        /// </summary>
        /// <param name="renderer">The design time renderer instance.</param>
        /// <param name="clipboard">The design time clipboard instance.</param>
        /// <param name="jsonSerializer">The design time Json serializer instance.</param>
        /// <param name="xamlSerializer">The design time Xaml serializer instance.</param>
        /// <returns>The new instance of the <see cref="DesignerContext"/> class.</returns>
        public static void InitializeContext(ShapeRenderer renderer, ITextClipboard clipboard, ITextSerializer jsonSerializer, ITextSerializer xamlSerializer)
        {
            // Editor

            Editor = new ProjectEditor()
            {
                CurrentTool     = Tool.Selection,
                CurrentPathTool = PathTool.Line,
                CommandManager  = new DesignerCommandManager(),
                Renderers       = new ShapeRenderer[] { renderer },
                ProjectFactory  = new ProjectFactory(),
                TextClipboard   = clipboard,
                JsonSerializer  = jsonSerializer,
                XamlSerializer  = xamlSerializer
            }.Defaults();

            // Recent Projects
            Editor.RecentProjects = Editor.RecentProjects.Add(RecentFile.Create("Test1", "Test1.project"));
            Editor.RecentProjects = Editor.RecentProjects.Add(RecentFile.Create("Test2", "Test2.project"));

            // Commands

            Editor.InitializeCommands();
            InitializeCommands(Editor);
            Editor.CommandManager.RegisterCommands();

            // New Project

            Editor.OnNew(null);

            // Data

            var db      = XDatabase.Create("Db");
            var fields  = new string[] { "Column0", "Column1" };
            var columns = ImmutableArray.CreateRange(fields.Select(c => XColumn.Create(db, c)));

            db.Columns = columns;
            var values = Enumerable.Repeat("<empty>", db.Columns.Length).Select(c => XValue.Create(c));
            var record = XRecord.Create(
                db,
                db.Columns,
                ImmutableArray.CreateRange(values));

            db.Records       = db.Records.Add(record);
            db.CurrentRecord = record;

            Database = db;
            Data     = XContext.Create(record);
            Record   = record;

            // Project

            IProjectFactory factory = new ProjectFactory();

            Project = factory.GetProject();

            Template = XContainer.CreateTemplate();

            Page = XContainer.CreatePage();
            var layer = Page.Layers.FirstOrDefault();

            layer.Shapes      = layer.Shapes.Add(XLine.Create(0, 0, null, null));
            Page.CurrentLayer = layer;
            Page.CurrentShape = layer.Shapes.FirstOrDefault();
            Page.Template     = Template;

            Document = XDocument.Create();
            Layer    = XLayer.Create();
            Options  = XOptions.Create();

            // State

            State = ShapeState.Create();

            // Style

            ArgbColor       = ArgbColor.Create();
            ArrowStyle      = ArrowStyle.Create();
            FontStyle       = FontStyle.Create();
            LineFixedLength = LineFixedLength.Create();
            LineStyle       = LineStyle.Create();
            Style           = ShapeStyle.Create("Default");
            TextStyle       = TextStyle.Create();

            // Shapes

            Arc             = XArc.Create(0, 0, Style, null);
            CubicBezier     = XCubicBezier.Create(0, 0, Style, null);
            Ellipse         = XEllipse.Create(0, 0, Style, null);
            Group           = XGroup.Create(Constants.DefaulGroupName);
            Image           = XImage.Create(0, 0, Style, null, "key");
            Line            = XLine.Create(0, 0, Style, null);
            Path            = XPath.Create("Path", Style, null);
            Point           = XPoint.Create();
            QuadraticBezier = XQuadraticBezier.Create(0, 0, Style, null);
            Rectangle       = XRectangle.Create(0, 0, Style, null);
            Text            = XText.Create(0, 0, Style, null, "Text");

            // Path

            ArcSegment                 = XArcSegment.Create(XPoint.Create(), XPathSize.Create(), 180, true, XSweepDirection.Clockwise, true, true);
            CubicBezierSegment         = XCubicBezierSegment.Create(XPoint.Create(), XPoint.Create(), XPoint.Create(), true, true);
            LineSegment                = XLineSegment.Create(XPoint.Create(), true, true);
            PathFigure                 = XPathFigure.Create(XPoint.Create(), false, true);
            PathGeometry               = XPathGeometry.Create(ImmutableArray.Create <XPathFigure>(), XFillRule.EvenOdd);
            PathSize                   = XPathSize.Create();
            PolyCubicBezierSegment     = XPolyCubicBezierSegment.Create(ImmutableArray.Create <XPoint>(), true, true);
            PolyLineSegment            = XPolyLineSegment.Create(ImmutableArray.Create <XPoint>(), true, true);
            PolyQuadraticBezierSegment = XPolyQuadraticBezierSegment.Create(ImmutableArray.Create <XPoint>(), true, true);
            QuadraticBezierSegment     = XQuadraticBezierSegment.Create(XPoint.Create(), XPoint.Create(), true, true);
        }
Ejemplo n.º 41
0
 public static void NodesOnXDocBeforeAndAfter()
 {
     XText aText = new XText("a"), bText = new XText("b");
     XElement a = new XElement("A", aText, bText);
     XDocument xDoc = new XDocument(a);
     IEnumerable<XNode> nodes = xDoc.Nodes();
     Assert.Equal(1, nodes.Count());
     a.Remove();
     Assert.Equal(0, nodes.Count());
 }
Ejemplo n.º 42
0
 private static bool IsWhiteSpace(XText textNode)
 {
     return(string.IsNullOrWhiteSpace(textNode.Value));
 }
Ejemplo n.º 43
0
        private CommandResult ExecuteProject(string path, XDocument document)
        {
            List <LogMessage> messages = null;

            foreach (XElement itemGroup in document.Root.Descendants("ItemGroup"))
            {
                XElement analyzers           = null;
                XElement formattingAnalyzers = null;

                foreach (XElement e in itemGroup.Elements("PackageReference"))
                {
                    string packageId = e.Attribute("Include")?.Value;

                    if (packageId == null)
                    {
                        continue;
                    }

                    if (packageId == "Roslynator.Formatting.Analyzers")
                    {
                        formattingAnalyzers = e;
                    }

                    if (packageId == "Roslynator.Analyzers")
                    {
                        analyzers = e;
                    }
                }

                if (analyzers == null)
                {
                    continue;
                }

                if (formattingAnalyzers != null)
                {
                    string versionText = formattingAnalyzers.Attribute("Version")?.Value;

                    if (versionText == null)
                    {
                        WriteXmlError(formattingAnalyzers, "Version attribute not found");
                        continue;
                    }

                    if (versionText != null)
                    {
                        Match match = _versionRegex.Match(versionText);

                        if (!match.Success)
                        {
                            WriteXmlError(formattingAnalyzers, $"Invalid version '{versionText}'");
                            continue;
                        }

                        versionText = match.Groups["version"].Value;

                        if (!Version.TryParse(versionText, out Version version))
                        {
                            WriteXmlError(formattingAnalyzers, $"Invalid version '{versionText}'");
                            continue;
                        }

                        if (version > Versions.Version_1_0_0 ||
                            !match.Groups["suffix"].Success)
                        {
                            continue;
                        }
                    }
                }

                if (formattingAnalyzers != null)
                {
                    var message = new LogMessage("Update package 'Roslynator.Formatting.Analyzers' to '1.0.0'", Colors.Message_OK, Verbosity.Normal);

                    (messages ?? (messages = new List <LogMessage>())).Add(message);

                    formattingAnalyzers.SetAttributeValue("Version", "1.0.0");
                }
                else
                {
                    var message = new LogMessage("Add package 'Roslynator.Formatting.Analyzers 1.0.0'", Colors.Message_OK, Verbosity.Normal);

                    (messages ?? (messages = new List <LogMessage>())).Add(message);

                    XText whitespace = null;

                    if (analyzers.NodesBeforeSelf().LastOrDefault() is XText xtext &&
                        xtext != null &&
                        string.IsNullOrWhiteSpace(xtext.Value))
                    {
                        whitespace = xtext;
                    }

                    analyzers.AddAfterSelf(whitespace, new XElement("PackageReference", new XAttribute("Include", "Roslynator.Formatting.Analyzers"), new XAttribute("Version", "1.0.0")));
                }
            }

            if (messages != null)
            {
                WriteUpdateMessages(path, messages);

                if (!DryRun)
                {
                    var settings = new XmlWriterSettings()
                    {
                        OmitXmlDeclaration = true
                    };

                    using (XmlWriter xmlWriter = XmlWriter.Create(path, settings))
                        document.Save(xmlWriter);
                }

                return(CommandResult.Success);
            }
            else
            {
                return(CommandResult.None);
            }
        }
Ejemplo n.º 44
0
 public ImmutableXText(XText other) : base(other)
 {
 }
Ejemplo n.º 45
0
 public static void ElementsBeforeSelfBeforeAndAfter()
 {
     XText aText = new XText("a"), bText = new XText("b");
     XElement a = new XElement("A", aText), b = new XElement("B", bText);
     aText.AddBeforeSelf(b);
     IEnumerable<XElement> nodes = aText.ElementsBeforeSelf();
     Assert.Equal(1, nodes.Count());
     b.Remove();
     Assert.Equal(0, nodes.Count());
 }
Ejemplo n.º 46
0
        /// <inheritdoc/>
        public override void Draw(object dc, XText text, double dx, double dy, ImmutableArray <XProperty> db, XRecord r)
        {
            var _gfx = dc as Graphics;

            var tbind = text.BindText(db, r);

            if (string.IsNullOrEmpty(tbind))
            {
                return;
            }

            Brush brush = ToSolidBrush(text.Style.Stroke);

            var fontStyle = System.Drawing.FontStyle.Regular;

            if (text.Style.TextStyle.FontStyle != null)
            {
                if (text.Style.TextStyle.FontStyle.Flags.HasFlag(Core2D.Style.FontStyleFlags.Bold))
                {
                    fontStyle |= System.Drawing.FontStyle.Bold;
                }

                if (text.Style.TextStyle.FontStyle.Flags.HasFlag(Core2D.Style.FontStyleFlags.Italic))
                {
                    fontStyle |= System.Drawing.FontStyle.Italic;
                }

                if (text.Style.TextStyle.FontStyle.Flags.HasFlag(Core2D.Style.FontStyleFlags.Underline))
                {
                    fontStyle |= System.Drawing.FontStyle.Underline;
                }

                if (text.Style.TextStyle.FontStyle.Flags.HasFlag(Core2D.Style.FontStyleFlags.Strikeout))
                {
                    fontStyle |= System.Drawing.FontStyle.Strikeout;
                }
            }

            Font font = new Font(
                text.Style.TextStyle.FontName,
                (float)(text.Style.TextStyle.FontSize * _textScaleFactor),
                fontStyle);

            var rect = CreateRect(
                text.TopLeft,
                text.BottomRight,
                dx, dy);

            var srect = new RectangleF(
                _scaleToPage(rect.X),
                _scaleToPage(rect.Y),
                _scaleToPage(rect.Width),
                _scaleToPage(rect.Height));

            var format = new StringFormat();

            switch (text.Style.TextStyle.TextHAlignment)
            {
            case TextHAlignment.Left:
                format.Alignment = StringAlignment.Near;
                break;

            case TextHAlignment.Center:
                format.Alignment = StringAlignment.Center;
                break;

            case TextHAlignment.Right:
                format.Alignment = StringAlignment.Far;
                break;
            }

            switch (text.Style.TextStyle.TextVAlignment)
            {
            case TextVAlignment.Top:
                format.LineAlignment = StringAlignment.Near;
                break;

            case TextVAlignment.Center:
                format.LineAlignment = StringAlignment.Center;
                break;

            case TextVAlignment.Bottom:
                format.LineAlignment = StringAlignment.Far;
                break;
            }

            format.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.NoClip;
            format.Trimming    = StringTrimming.None;

            _gfx.DrawString(
                tbind,
                font,
                ToSolidBrush(text.Style.Stroke),
                srect,
                format);

            brush.Dispose();
            font.Dispose();
        }