public static void ToXmlReturnsNewXElement()
        {
            var element  = new XElement("Tjoho");
            var fragment = SourceFragment.FromXml(element);

            Assert.AreNotEqual(element, fragment.ToXml());
        }
Beispiel #2
0
        /// <summary>
        /// 根据指定类型<see cref="DbDataSetExpression"/>表达式创建数据源语句片段。
        /// </summary>
        /// <param name="context">生成上下文。</param>
        /// <param name="expression">指定表达式。</param>
        /// <returns>创建结果。</returns>
        protected virtual ISourceFragment CreateSourceForDataSet(GenerateContext context, DbExpression expression)
        {
            var            content  = (DbDataSetExpression)expression;
            var            metadata = context.Metadata.Table(content.Item.ClrType);
            SourceFragment table    = null;

            if (metadata.InheritSets.Length > 0)
            {
                if (content.Name != null)
                {
                    throw new NotSupportedException(Res.NotSupportedInheritSetUsingDbName);
                }
                table = new InheritFragment(context, metadata);
            }
            else
            {
                table = new TableFragment(context, content);
            }
            context.RegisterSource(content.Item, table);
            context.RegisterSource(content, table);
            if (IsSelectFragment(content))
            {
                return(InitialSelectFragment(new SelectFragment(context, table), content));
            }
            if (table is InheritFragment inherit)
            {
                inherit.Initialize();
            }
            return(table);
        }
        public static void ToStringIsRoundtripInvariant()
        {
            var fragmentString  = Fragment.ToString();
            var trippedFragment = SourceFragment.FromString(fragmentString);

            Assert.AreEqual(Fragment, trippedFragment);
        }
        LiveElement CreateChildElement(SourceFragment sourceFragment)
        {
            var elm = new LiveElement(parent: this);

            elm.UpdateFrom(sourceFragment.ToXml());
            return(elm);
        }
        static IControl CreateGradientRow(IElement linearGradient, IEditorFactory editors)
        {
            var name = linearGradient.UxName();

            var stops = linearGradient.Children
                        .Where(e => e.Is("Fuse.Drawing.GradientStop"));

            return(Layout.StackFromTop(
                       editors.NameRow("Gradient Name", name),

                       Spacer.Medium,

                       stops
                       .PoolPerElement((index, gradientStop) =>
                                       CreateGradientStopRow(index, gradientStop.Switch(), editors))
                       .StackFromTop(separator: () => Spacer.Small),

                       Spacer.Medium,

                       Buttons.DefaultButton(
                           text: "Remove Gradient Stop",
                           cmd: stops
                           .Select(s =>
                                   s.LastOrNone().MatchWith(
                                       some: stop => Command.Enabled(() => stop.Cut()),
                                       none: () => Command.Disabled))
                           .Switch()),

                       Spacer.Small,

                       Buttons.DefaultButton(
                           text: "Add Gradient Stop",
                           cmd: Command.Enabled(() => linearGradient.Paste(SourceFragment.FromString("<GradientStop Offset=\"1\"/>"))))));
        }
Beispiel #6
0
        /// <summary>
        /// Creates a new document in the project, and adds it to unoproj file.
        /// Also creates any missing directories in path.
        /// </summary>
        public async Task CreateDocument(RelativeFilePath relativePath, SourceFragment contents = null)
        {
            contents = contents ?? SourceFragment.Empty;

            var rootDir = await RootDirectory.FirstAsync();

            var newFilePath = rootDir.Combine(relativePath);

            var containingDir = newFilePath.ContainingDirectory;

            _shell.Create(containingDir);

            using (var stream = _shell.CreateNew(newFilePath))
            {
                var bytes = contents.ToBytes();
                stream.Write(bytes, 0, bytes.Length);
            }

            var projectFilePath = await FilePath.FirstAsync();

            var project = Uno.ProjectFormat.Project.Load(projectFilePath.NativePath);

            if (project.AllFiles.None(item => item.UnixPath == relativePath.NativeRelativePath))
            {
                project.MutableIncludeItems.Add(new Uno.ProjectFormat.IncludeItem(relativePath.NativeRelativePath));
                project.Save();
            }
        }
        public static void ToXmlIsRoundtripInvariant()
        {
            var fragmentXml     = Fragment.ToXml();
            var trippedFragment = SourceFragment.FromXml(fragmentXml);

            Assert.AreEqual(Fragment, trippedFragment);
        }
Beispiel #8
0
        public void Mutate(XElement element)
        {
            var descendants = element.Descendants().ToList();

            if ((descendants.Count < _maxElements / 2 || _rng.NextDouble() > descendants.Count / (double)_maxElements) &&
                descendants.Count < _maxElements)
            {
                var containers         = descendants.Count > 0 ? descendants.Where(x => x.Name.LocalName == "Grid") : new[] { element };
                var container          = RandomItem(containers);
                var existingChildCount = container.Elements().Count();
                var insertPoint        = _rng.Next(0, existingChildCount + 1);

                var insertElement = SourceFragment.FromString(
                    String.Format(
                        "<Grid ChildOrder=\"{0}\" Background=\"{1}\" />",
                        Depth(container) % 2 == 0 ? "RowMajor" : "ColumnMajor",
                        RandomItem(_colors)))
                                    .ToXml();

                if (insertPoint == existingChildCount)
                {
                    container.Add(insertElement);
                }
                else
                {
                    container.Elements().ElementAt(insertPoint).AddBeforeSelf(insertElement);
                }
            }
            else
            {
                RandomItem(descendants).Remove();
            }
        }
        static SourceFragment RemoveIndentFromDescendantNodes(SourceFragment fragment, string elementIndent)
        {
            // If all subsequent lines start with the indent specified, remove it
            StringBuilder stringBuilder    = new StringBuilder();
            bool          isFirst          = true;
            bool          indentFixSuccess = true;

            foreach (var line in fragment.ToString().Split('\n'))
            {
                if (isFirst)
                {
                    isFirst = false;
                    stringBuilder.Append(line);
                }
                else if (!line.StartsWith(elementIndent))
                {
                    indentFixSuccess = false;
                    break;
                }
                else
                {
                    stringBuilder.Append('\n');
                    stringBuilder.Append(line.Substring(elementIndent.Length));
                }
            }
            return(indentFixSuccess ? SourceFragment.FromString(stringBuilder.ToString()) : fragment);
        }
Beispiel #10
0
 public static IControl Create(IElement element, IEditorFactory editors)
 {
     return(editors.ElementList(
                "Shadow", element,
                SourceFragment.FromString("<Shadow/>"),
                shadow => CreateShadowRow(shadow, editors)
                .WithInspectorPadding()));
 }
Beispiel #11
0
 public static IControl Create(IElement element, IEditorFactory editors)
 {
     return(editors.ElementList(
                "Solid Color", element,
                SourceFragment.FromString("<SolidColor/>"),
                solidColor => CreateSolidColorRow(solidColor, editors)
                .WithInspectorPadding()));
 }
Beispiel #12
0
        /// <summary>
        /// 指定源设置<see cref="Current"/>,然后执行相应活动。
        /// </summary>
        /// <param name="action">执行活动。</param>
        /// <param name="fragment">目标源。</param>
        public void Enter(Action action, SourceFragment fragment)
        {
            var old = Current;

            Current = fragment;
            action();
            Current = old;
        }
Beispiel #13
0
 public static IControl Create(IElement element, IEditorFactory editors)
 {
     return(editors.ElementList(
                "Rotation", element,
                SourceFragment.FromString("<Rotation/>"),
                rotation => CreateRotationRow(rotation, editors)
                .WithInspectorPadding()));
 }
Beispiel #14
0
 public static IControl Create(IElement element, IEditorFactory editors)
 {
     return(editors.ElementList(
                "Stroke", element,
                SourceFragment.FromString("<Stroke Width=\"3\" Color=\"#f00\"/>"),
                stroke => CreateStrokeRow(stroke, editors)
                .WithInspectorPadding())
            .MakeCollapsable(RectangleEdge.Top, element.Is("Fuse.Controls.Shape")));
 }
        public IElement Paste(SourceFragment fragment)
        {
            var child = CreateChildElement(fragment);

            UpdateXml(e => e.AddIndented(child.Element));
            UpdateChildren(c => c.Add(child));

            return(child);
        }
Beispiel #16
0
        public void Mutate(AbsoluteFilePath file, int iterations)
        {
            var element = SourceFragment.FromString(File.ReadAllText(file.NativePath)).ToXml();

            for (int i = 0; i < iterations; i++)
            {
                Mutate(element);
            }
            File.WriteAllText(file.NativePath, SourceFragment.FromXml(element).ToString());
        }
        public Task <SourceFragment> Copy()
        {
            var    fragment = SourceFragment.FromXml(Element);
            string elementIndent;

            if (Element.TryGetElementIndent(out elementIndent))
            {
                fragment = RemoveIndentFromDescendantNodes(fragment, elementIndent);
            }
            return(Task.FromResult(fragment));
        }
 public static IControl Create(IElement element, IEditorFactory editors)
 {
     return(editors.ElementList(
                "Linear Gradient", element,
                SourceFragment.FromString(
                    "<LinearGradient>\n" +
                    "\t<GradientStop Offset=\"0\" Color=\"#ADDDAB\"/>\n" +
                    "\t<GradientStop Offset=\"1\" Color=\"#6DC0D2\"/>\n" +
                    "</LinearGradient>\n"),
                linearGradient => CreateGradientRow(linearGradient, editors)
                .WithInspectorPadding()));
 }
 public static void WriteDataIsRoundtripInvariant()
 {
     using (var stream = new MemoryStream())
         using (var reader = new BinaryReader(stream))
             using (var writer = new BinaryWriter(stream))
             {
                 Fragment.WriteTo(writer);
                 stream.Seek(0, SeekOrigin.Begin);
                 var trippedFragment = SourceFragment.ReadFrom(reader);
                 Assert.AreEqual(Fragment, trippedFragment);
             }
 }
Beispiel #20
0
        static IElement CreateTree(string xmlText = "<Parent><FirstChild /><SecondChild /></Parent>")
        {
            var parent = new LiveElement(
                AbsoluteFilePath.Parse("foo/bar"),
                Observable.Never <ILookup <Simulator.ObjectIdentifier, Simulator.ObjectIdentifier> >(),
                Observable.Return(true),
                new Subject <Unit>(),
                Observer.Create <IBinaryMessage>(msg => { }),
                s => Element.Empty);

            parent.UpdateFrom(SourceFragment.FromString(xmlText).ToXml());

            return(parent);
        }
Beispiel #21
0
        public static async Task Copy_element_spanning_several_lines_removes_outer_indentation(string initial, string expected)
        {
            Console.WriteLine("Initial:\n{0}\n", initial.Replace("\t", "⭾"));
            var root = (LiveElement)CreateTree();

            root.UpdateFrom(SourceFragment.FromString(initial).ToXml());
            var parent = (await root.Children.FirstAsync()).First();
            var copied = (await parent.Children.WherePerElement(x => x.Name.Is("Copied")).FirstAsync()).First();
            var actual = (await copied.Copy()).ToString();

            Console.WriteLine("Expected:\n{0}\n", expected.Replace("\t", "⭾"));
            Console.WriteLine("Actual:\n{0}\n", actual.Replace("\t", "⭾"));
            Assert.That(actual, Is.EqualTo(expected.Replace("\n", Environment.NewLine)));
        }
        public IElement PasteAfter(SourceFragment fragment)
        {
            if (!_parent.HasValue)
            {
                throw new ElementIsRoot();
            }

            var sibling = _parent.Value.CreateChildElement(fragment);

            UpdateXml(e => e.AddAfterSelfIndented(sibling.Element));
            _parent.Value.UpdateChildren(c => c.Insert(c.IndexOf(this) + 1, sibling));

            return(sibling);
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="PrevFragmentData">Timing data for the previous fragment</param>
        /// <param name="Fragment">The fragment to compile</param>
        /// <param name="CompilerExe">Path to the compiler</param>
        /// <param name="ResponseFile">Path to the compiler response file</param>
        /// <param name="LogFile">Path to the log file</param>
        public FragmentTimingData(string UniqueName, string Digest, FragmentTimingData PrevFragmentData, SourceFragment[] Fragments, List <Tuple <int, SourceFile> > IncludeHistory, FileReference IntermediateFile, CompileEnvironment CompileEnvironment)
        {
            this.UniqueName         = UniqueName;
            this.Digest             = Digest;
            this.PrevFragmentData   = PrevFragmentData;
            this.Fragment           = Fragments[Fragments.Length - 1];
            this.IntermediateFile   = IntermediateFile;
            this.CompileEnvironment = CompileEnvironment;

            // Write the source file
            using (StreamWriter Writer = new StreamWriter(IntermediateFile.FullName))
            {
                int IncludeHistoryIdx          = 0;
                List <SourceFile> IncludeStack = new List <SourceFile>();
                for (int Idx = 0; Idx < Fragments.Length; Idx++)
                {
                    SourceFragment Fragment = Fragments[Idx];

                    // Figure out which tag it's bound to
                    int Tag = (Fragment.File.Counterpart == null)? Idx : -1;

                    // Update the stack for new includes
                    while (IncludeHistoryIdx < IncludeHistory.Count && IncludeHistory[IncludeHistoryIdx].Item1 == Idx)
                    {
                        if (IncludeHistory[IncludeHistoryIdx].Item2 == null)
                        {
                            SourceFile IncludeFile = IncludeStack[IncludeStack.Count - 1];
                            IncludeStack.RemoveAt(IncludeStack.Count - 1);
                            Writer.WriteLine("{0}// END INCLUDE {1}", new string(' ', IncludeStack.Count * 4), IncludeFile.Location.FullName);
                            IncludeHistoryIdx++;
                        }
                        else if (IncludeHistoryIdx + 1 < IncludeHistory.Count && IncludeHistory[IncludeHistoryIdx + 1].Item2 == null)
                        {
                            IncludeHistoryIdx += 2;
                        }
                        else
                        {
                            SourceFile IncludeFile = IncludeHistory[IncludeHistoryIdx].Item2;
                            Writer.WriteLine("{0}// INCLUDE {1}", new string(' ', IncludeStack.Count * 4), IncludeFile.Location.FullName);
                            IncludeStack.Add(IncludeFile);
                            IncludeHistoryIdx++;
                        }
                    }

                    // Get the text for this node
                    Writer.WriteLine("{0}#include \"{1}\"", new string(' ', (IncludeStack.Count - 0) * 4), Fragment.Location.FullName);
                }
            }
        }
Beispiel #24
0
        public static async Task Paste()
        {
            var parent        = CreateTree();
            var siblings      = (await parent.Children.FirstAsync()).ToImmutableList();
            var childFragment = SourceFragment.FromString("<TheThing/>");
            var child         = parent.Paste(childFragment);

            var newSiblings = await parent.Children.FirstAsync();

            Assert.That(newSiblings, Is.EqualTo(siblings.Add(child)));

            var src = await parent.Copy();

            Assert.That(src.ToString(), Is.EqualTo("<Parent><FirstChild /><SecondChild /><TheThing /></Parent>"));
        }
Beispiel #25
0
        async Task ExtractClassToFile(IElement element, string name, RelativeFilePath fileName)
        {
            var xml = (await element.Copy()).ToXml();

            xml.SetAttributeValue(KeyToName("ux:Class"), name);
            await _project.CreateDocument(fileName, SourceFragment.FromXml(xml));

            // Don't replace original element before new class is loaded
            await _project.Classes
            .WherePerElement(x => x.UxClass().Is(name))
            .Where(x => x.Any())
            .FirstAsync()
            .Timeout(TimeSpan.FromSeconds(2));

            await element.Replace(_ => Task.FromResult(SourceFragment.FromString(string.Format("<{0} />", name))));
        }
        static IElement CreateRootElement(SourceFragment fragment, string filename)
        {
            var parent = new LiveElement(
                AbsoluteFilePath.Parse("/project/" + filename),
                Observable.Never <ILookup <ObjectIdentifier, ObjectIdentifier> >(),
                Observable.Return(true),
                new Subject <Unit>(),
                Observer.Create <IBinaryMessage>(msg => { }),
                s => Element.Empty);

            // Panel is an example of an instance
            // Circle is an example of a class (called MyClass)
            parent.UpdateFrom(fragment.ToXml());

            return(parent);
        }
        static IElement CreateTree(string uxSource)
        {
            var parent = new LiveElement(
                AbsoluteFilePath.Parse("foo/bar"),
                Observable.Never <ILookup <Simulator.ObjectIdentifier, Simulator.ObjectIdentifier> >(),
                Observable.Return(true),
                new Subject <Unit>(),
                Observer.Create <IBinaryMessage>(msg => { }),
                s => Element.Empty);

            // Panel is an example of an instance
            // Circle is an example of a class (called MyClass)
            parent.UpdateFrom(SourceFragment.FromString(uxSource).ToXml());

            return(parent);
        }
Beispiel #28
0
        public static async Task Cut_indents_surrounding_remaining_area(string initial, string expected)
        {
            Console.WriteLine("Initial:\n{0}\n", initial.Replace("\t", "⭾"));
            var root = (LiveElement)CreateTree();

            root.UpdateFrom(SourceFragment.FromString(initial).ToXml());
            var parent = (await root.Children.FirstAsync()).First();

            var removed = (await parent.Children.WherePerElement(x => x.Name.Is("Removed")).FirstAsync()).First();
            await removed.Cut();

            var src = await root.Copy();

            Console.WriteLine("Expected:\n{0}\n", expected.Replace("\t", "⭾"));
            var actual = src.ToString();

            Console.WriteLine("Actual:\n{0}\n", actual.Replace("\t", "⭾"));
            Assert.That(actual, Is.EqualTo(expected.Replace("\n", Environment.NewLine)));
        }
Beispiel #29
0
        public static async Task Paste_in_root_indents_element_using_tab_by_default(string initial, string pasted, string expected)
        {
            Console.WriteLine("Initial:\n{0}\n", initial.Replace("\t", "⭾"));
            var root = (LiveElement)CreateTree();

            root.UpdateFrom(SourceFragment.FromString(initial).ToXml());

            var childFragment = SourceFragment.FromString(pasted);

            root.Paste(childFragment);

            var src = await root.Copy();

            Console.WriteLine("Expected:\n{0}\n", expected.Replace("\t", "⭾"));
            var actual = src.ToString();

            Console.WriteLine("Actual:\n{0}\n", actual.Replace("\t", "⭾"));
            Assert.That(actual, Is.EqualTo(expected.Replace("\n", Environment.NewLine)));
        }
Beispiel #30
0
        public async Task ExtractClass(IElement element, string name, Optional <RelativeFilePath> fileName)
        {
            try
            {
                if (fileName.HasValue)
                {
                    await ExtractClassToFile(element, name, fileName.Value);

                    return;
                }

                element.UxClass().Write(name);
                element.PasteAfter(SourceFragment.FromString(string.Format("<{0} />", name)));
            }
            catch (Exception ex)
            {
                _logMessages.OnNext(string.Format("Error: Unable to create class. {0}\r\n", ex.Message));
            }
        }