Beispiel #1
0
        /// <summary>
        /// Writes the node tree to a stream</summary>
        /// <param name="root">Node tree to write</param>
        /// <param name="stream">Write stream</param>
        /// <param name="uri">URI of stream</param>
        public virtual void Write(DomNode root, Stream stream, Uri uri)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.IndentChars = "\t";
            settings.NewLineHandling = NewLineHandling.Replace;
            settings.NewLineChars = "\r\n";

            XmlWriter writer = null;
            try
            {
                m_uri = uri;

                writer = XmlWriter.Create(stream, settings);
                writer.WriteStartDocument();

                m_root = root;

                WriteElement(root, writer);

                writer.WriteEndDocument();
            }
            finally
            {
                if (writer != null)
                    ((IDisposable)writer).Dispose();

                m_uri = null;
                m_root = null;
            }
        }
        /// <summary>
        /// Performs custom actions for a node that has been removed from the DOM subtree</summary>
        /// <param name="node">Removed node</param>
        protected override void RemoveNode(DomNode node)
        {
            foreach (DomNode dependency in GetDependencies(node))
                m_dependencySystem.RemoveDependency(node, dependency);

            base.RemoveNode(node);
        }
Beispiel #3
0
        public void TestValidate()
        {
            DomNodeType childType = new DomNodeType("child");
            DomNodeType parentType = new DomNodeType("parent");
            ChildInfo childInfo = new ChildInfo("child", childType, true);
            parentType.Define(childInfo);
            DomNode parent = new DomNode(parentType);
            IList<DomNode> childList = parent.GetChildList(childInfo);
            DomNode child1 = new DomNode(childType);
            DomNode child2 = new DomNode(childType);
            DomNode child3 = new DomNode(childType);

            ChildCountRule test = new ChildCountRule(1, 2);
            
            // 0 children. Not valid.
            Assert.False(test.Validate(parent, null, childInfo));

            // 1 child. Valid.
            childList.Add(child1);
            Assert.True(test.Validate(parent, null, childInfo));
            
            // 2 children. Valid.
            childList.Add(child2);
            Assert.True(test.Validate(parent, null, childInfo));

            // 3 children. Not valid.
            childList.Add(child3);
            Assert.False(test.Validate(parent, null, childInfo));

            // 0 children. Not valid.
            childList.Clear();
            Assert.False(test.Validate(parent, null, childInfo));
        }
        public void Traverse(DomNode root)
        {
            DomNode node = root;
            int depth = 0;

            while (node != null) {
                visitor.Head(node, depth);
                if (node.ChildNodes.Count > 0) {
                    node = node.ChildNode(0);
                    depth++;
                }

                else {
                    while (node.NextSibling == null && depth > 0) {
                        visitor.Tail(node, depth);
                        node = node.ParentNode;
                        depth--;
                    }
                    visitor.Tail(node, depth);
                    if (node == root)
                        break;
                    node = node.NextSibling;
                }
            }
        }
Beispiel #5
0
		string GetNodeTitle(DomNode node)
		{
			StringBuilder b = new StringBuilder();
			b.Append(DecodeRole(node.Role, node.Parent != null ? node.Parent.GetType() : null));
			b.Append(": ");
			b.Append(node.GetType().Name);
			bool hasProperties = false;
			foreach (PropertyInfo p in node.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) {
				if (p.Name == "NodeType" || p.Name == "IsNull")
					continue;
				if (p.PropertyType == typeof(string) || p.PropertyType.IsEnum || p.PropertyType == typeof(bool)) {
					if (!hasProperties) {
						hasProperties = true;
						b.Append(" (");
					} else {
						b.Append(", ");
					}
					b.Append(p.Name);
					b.Append(" = ");
					try {
						object val = p.GetValue(node, null);
						b.Append(val != null ? val.ToString() : "**null**");
					} catch (TargetInvocationException ex) {
						b.Append("**" + ex.InnerException.GetType().Name + "**");
					}
				}
			}
			if (hasProperties)
				b.Append(")");
			return b.ToString();
		}
Beispiel #6
0
        public void TestBaseType()
        {
            DomNodeType test = new DomNodeType("test");
            Assert.AreEqual(test.BaseType, DomNodeType.BaseOfAllTypes);
            DomNodeType baseType = new DomNodeType("base");
            test.BaseType = baseType;
            Assert.AreEqual(test.BaseType, baseType);

            DomNode node = new DomNode(test);
            // base type is now frozen
            Assert.Throws<InvalidOperationException>(delegate { test.BaseType = new DomNodeType("newBase"); });

            test = new DomNodeType(
                "test",
                null,
                EmptyEnumerable<AttributeInfo>.Instance,
                EmptyEnumerable<ChildInfo>.Instance,
                EmptyEnumerable<ExtensionInfo>.Instance);

            Assert.AreEqual(test.BaseType, DomNodeType.BaseOfAllTypes);
            test.BaseType = baseType;
            Assert.AreEqual(test.BaseType, baseType);

            node = new DomNode(test);
            Assert.Throws<InvalidOperationException>(delegate { test.BaseType = new DomNodeType("newBase"); });
        }
Beispiel #7
0
        public void TestBaseType()
        {
            DomNodeType test = new DomNodeType("test");
            Assert.AreEqual(test.BaseType, DomNodeType.BaseOfAllTypes);
            DomNodeType baseType = new DomNodeType("base");
            test.BaseType = baseType;
            Assert.AreEqual(test.BaseType, baseType);

            #pragma warning disable 219 //Disable the unused local variable warning. We need the side-effect of creating the DomNode.
            DomNode node = new DomNode(test);
            #pragma warning restore 219
            // base type is now frozen
            Assert.Throws<InvalidOperationException>(delegate { test.BaseType = new DomNodeType("newBase"); });

            test = new DomNodeType(
                "test",
                null,
                EmptyEnumerable<AttributeInfo>.Instance,
                EmptyEnumerable<ChildInfo>.Instance,
                EmptyEnumerable<ExtensionInfo>.Instance);

            Assert.AreEqual(test.BaseType, DomNodeType.BaseOfAllTypes);
            test.BaseType = baseType;
            Assert.AreEqual(test.BaseType, baseType);

            // ReSharper disable once RedundantAssignment
            node = new DomNode(test);
            Assert.Throws<InvalidOperationException>(delegate { test.BaseType = new DomNodeType("newBase"); });
        }
Beispiel #8
0
 public Expression CreateExpression()
 {
     Expression exp = new DomNode(Schema.expressionType.Type).Cast<Expression>();
     exp.Id = "Expression";
     exp.Label = "Expression".Localize();
     return exp;
 }
Beispiel #9
0
        /// <summary>
        /// Finish MEF intialization for the component by creating DomNode tree for application data.</summary>
        void IInitializable.Initialize()
        {
            m_mainform.Shown += (sender, e) =>
                {
                    // create root node.
                    var rootNode = new DomNode(Schema.gameType.Type, Schema.gameRootElement);
                    rootNode.SetAttribute(Schema.gameType.nameAttribute, "Game");

                    // create Orc game object and add it to rootNode.
                    var orc = CreateOrc();
                    rootNode.GetChildList(Schema.gameType.gameObjectChild).Add(orc);

                    // add a child Orc.
                    var orcChildList = orc.GetChildList(Schema.orcType.orcChild);
                    orcChildList.Add(CreateOrc("Child Orc1"));

                    rootNode.InitializeExtensions();

                    var edContext = rootNode.Cast<GameEditingContext>();
                    edContext.Set(orc);

                    // set active context and select orc object.
                    m_contextRegistry.ActiveContext = rootNode;
                    
                };
        }
Beispiel #10
0
        /// <summary>
        /// Constructor</summary>
        /// <param name="input">DomNode</param>
        /// <param name="mesh">Mesh</param>
        public PrimInput(DomNode input, Mesh mesh)
        {
            AttributeInfo srcAttrib = null;
            AttributeInfo offsetAttrib = null;
            AttributeInfo semantiAttrib = null;

            if (input.Type == Schema.InputLocalOffset.Type)
            {
                srcAttrib = Schema.InputLocalOffset.sourceAttribute;
                offsetAttrib = Schema.InputLocalOffset.offsetAttribute;
                semantiAttrib = Schema.InputLocalOffset.semanticAttribute;                
            }
            else if (input.Type == Schema.InputLocal.Type)
            {
                srcAttrib = Schema.InputLocal.sourceAttribute;                
                semantiAttrib = Schema.InputLocal.semanticAttribute;                
            }
            else
            {
                throw new ArgumentException(input.Type.ToString() + " is not supported");
            }


            // find the source for this input.
            string srcId = (string)input.GetAttribute(srcAttrib);
            srcId = srcId.Replace("#", "").Trim();

            foreach (Source src in mesh.Sources)
            {
                if (src.Id == srcId)
                {
                    m_source = src;
                    break;
                }
            }

            if (offsetAttrib != null)
                m_offset = Convert.ToInt32(input.GetAttribute(offsetAttrib));
            else
                m_offset = -1;

            m_semantic = (string)input.GetAttribute(semantiAttrib);

            switch (m_semantic)
            {
                case "POSITION":
                    m_atgiName = "position";
                    break;
                case "NORMAL":
                    m_atgiName = "normal";
                    break;
                case "TEXCOORD":
                    m_atgiName = "map1";
                    break;
                case "COLOR":
                    m_atgiName = "color";
                    break;
            }      

        }
Beispiel #11
0
        /// <summary>
        /// Does a command</summary>
        /// <param name="commandTag">Command</param>
        void ICommandClient.DoCommand(object commandTag)
        {
            if (CommandTag.AddLayerFolder.Equals(commandTag))
            {
                LayerFolder newLayer = new DomNode(LayerFolderType).As<LayerFolder>();
                newLayer.Name = "New Layer".Localize();

                IList<LayerFolder> layerList = null;
                object target = m_targetRef.Target;
                if (target != null)
                {
                    LayerFolder parentLayer = target.As<LayerFolder>();
                    if (parentLayer != null)
                        layerList = parentLayer.Folders;
                    else
                    {
                        LayeringContext layeringContext = target.As<LayeringContext>();
                        if (layeringContext != null)
                            layerList = layeringContext.Layers;
                    }
                }

                if (layerList != null)
                {
                    ILayeringContext layeringContext = m_contextRegistry.GetMostRecentContext<ILayeringContext>();
                    ITransactionContext transactionContext = layeringContext.As<ITransactionContext>();
                    transactionContext.DoTransaction(() => layerList.Add(newLayer), "Add Layer".Localize());
                }
            }
        }
Beispiel #12
0
        /// <summary>
        /// Creates game using raw DomNode</summary>        
        private static DomNode CreateGameUsingDomNode()
        {                                     
            // create Dom node of the root type defined by the schema
            DomNode game = new DomNode(GameSchema.gameType.Type, GameSchema.gameRootElement);
            game.SetAttribute(GameSchema.gameType.nameAttribute, "Ogre Adventure II");
            IList<DomNode> childList = game.GetChildList(GameSchema.gameType.gameObjectChild);

            // Add an ogre
            DomNode ogre = new DomNode(GameSchema.ogreType.Type);
            ogre.SetAttribute(GameSchema.ogreType.nameAttribute, "Bill");
            ogre.SetAttribute(GameSchema.ogreType.sizeAttribute, 12);
            ogre.SetAttribute(GameSchema.ogreType.strengthAttribute, 100);
            childList.Add(ogre);


            // Add a dwarf
            DomNode dwarf = new DomNode(GameSchema.dwarfType.Type);
            dwarf.SetAttribute(GameSchema.dwarfType.nameAttribute, "Sally");
            dwarf.SetAttribute(GameSchema.dwarfType.ageAttribute, 32);
            dwarf.SetAttribute(GameSchema.dwarfType.experienceAttribute, 55);
            childList.Add(dwarf);

            // Add a tree
            DomNode tree = new DomNode(GameSchema.treeType.Type);
            tree.SetAttribute(GameSchema.treeType.nameAttribute, "Mr. Oak");
            childList.Add(tree);

            return game;           
        }
Beispiel #13
0
 /// <summary>
 /// Creates a new UIRef adapter and underlying DomNode</summary>
 /// <param name="uiObj">UIObject being referenced</param>
 /// <returns>New UIRef adapter</returns>
 public static UIRef New(UIObject uiObj)
 {
     DomNode node = new DomNode(UISchema.UIRefType.Type);
     UIRef uiRef = node.As<UIRef>();
     uiRef.UIObject = uiObj;
     return uiRef;
 }
Beispiel #14
0
        public void TestDefaultValue()
        {
            AttributeType type = new AttributeType("test", typeof(string));
            AttributeInfo test = new AttributeInfo("test", type);
            test.DefaultValue = "foo";
            Assert.AreEqual(test.DefaultValue, "foo");
            test.DefaultValue = null;
            Assert.AreEqual(test.DefaultValue, type.GetDefault());
            Assert.Throws<InvalidOperationException>(delegate { test.DefaultValue = 1; });

            AttributeType length2Type = new AttributeType("length2Type", typeof(int[]), 2);
            AttributeInfo length2Info = new AttributeInfo("length2", length2Type);
            Assert.AreEqual(length2Info.DefaultValue, length2Type.GetDefault());
            Assert.AreEqual(length2Info.DefaultValue, new int[] { default(int), default(int) });
            DomNodeType nodeType = new DomNodeType("testNodeType");
            nodeType.Define(length2Info);
            DomNode node = new DomNode(nodeType);
            Assert.AreEqual(node.GetAttribute(length2Info), length2Info.DefaultValue);
            node.SetAttribute(length2Info, new int[] { 1, 2 });
            Assert.AreEqual(node.GetAttribute(length2Info), new int[] { 1, 2 });
            node.SetAttribute(length2Info, new int[] { 1 });
            Assert.AreEqual(node.GetAttribute(length2Info), new int[] { 1 });

            AttributeType length1Type = new AttributeType("length1Type", typeof(int[]), 1);
            AttributeInfo length1Info = new AttributeInfo("length1", length1Type);
            Assert.AreEqual(length1Info.DefaultValue, length1Type.GetDefault());
            Assert.AreEqual(length1Info.DefaultValue, new int[] { default(int) });
            nodeType = new DomNodeType("testNodeType");
            nodeType.Define(length1Info);
            node = new DomNode(nodeType);
            Assert.AreEqual(node.GetAttribute(length1Info), length1Info.DefaultValue);
            node.SetAttribute(length1Info, new int[] { 1 });
            Assert.AreEqual(node.GetAttribute(length1Info), new int[] { 1 });
        }
Beispiel #15
0
        /// <summary>
        /// Creates game using DomNode adapter</summary>        
        private static DomNode CreateGameUsingDomNodeAdapter()
        {
            // create game.
            DomNode root = new DomNode(GameSchema.gameType.Type, GameSchema.gameRootElement);
            Game game = root.As<Game>();
            game.Name = "Ogre Adventure II";

            // Add an ogre
            DomNode ogreNode = new DomNode(GameSchema.ogreType.Type);
            Ogre orge = ogreNode.As<Ogre>();
            orge.Name = "Bill";
            orge.Size = 12;
            orge.Strength = 100;
            game.GameObjects.Add(orge);

            // Add a dwarf
            DomNode dwarfNode = new DomNode(GameSchema.dwarfType.Type);
            Dwarf dwarf = dwarfNode.As<Dwarf>();
            dwarf.Name = "Sally";
            dwarf.Age = 32;
            dwarf.Experience = 55;
            game.GameObjects.Add(dwarf);

            // Add a tree
            DomNode treeNode = new DomNode(GameSchema.treeType.Type);
            GameObject tree = treeNode.As<GameObject>();
            tree.Name = "Mr. Oak";
            game.GameObjects.Add(tree);

            return game.DomNode;
        }
Beispiel #16
0
        /// <summary>
        /// Imports templates and template folders stored in an external file</summary>
        /// <param name="toFolder">Template folder in which to import templates and template folders</param>
        /// <param name="fromRoot">Root of templates to import</param>
        /// <param name="uri"></param>
        internal void ImportTemplates(DomNode toFolder, DomNode fromRoot, Uri uri)
        {
            TagTemplateTree(fromRoot, uri);
 
            // assume all templates and their containing folders are children of a root template folder 
            foreach (var domNode in fromRoot.LevelSubtree) // add top-level folders
            {
                if (domNode.Type == Schema.templateFolderType.Type) // this should be the root template folder of the imported DOM tree
                {
                    // import the children of the root template folder, but not the root itself
                    foreach (var child in domNode.Children.ToArray())
                    {
                        if (child.Type == Schema.templateFolderType.Type)
                        {
                            toFolder.GetChildList(Schema.templateFolderType.templateFolderChild).Add(child);
                        }
                        else if (child.Type == Schema.templateType.Type)
                        {
                            toFolder.GetChildList(Schema.templateFolderType.templateChild).Add(child);
                        }
                    }
                    break; // skip the rest of the document contents
                }
            }
        }
Beispiel #17
0
        // Tests http://tracker.ship.scea.com/jira/browse/WWSATF-1370
        // Test adding two types of extensions that have the same Name but different FullName.
        public void TestDuplicateNames()
        {
            var domType = new DomNodeType("domType");
            var extension = new ExtensionInfo<TestExtensionInfo>();
            domType.Define(extension);

            var domDerivedType = new DomNodeType("domDerivedType", domType);
            var anotherExtension = new ExtensionInfo<AnotherName.TestExtensionInfo>();
            domDerivedType.Define(anotherExtension);

            var domNode = new DomNode(domDerivedType);
            domNode.InitializeExtensions();
            Assert.IsTrue(domNode.GetExtension(extension).GetType() == typeof(TestExtensionInfo));
            Assert.IsTrue(domNode.GetExtension(anotherExtension).GetType() == typeof(AnotherName.TestExtensionInfo));

            ExtensionInfo getInfo = domType.GetExtensionInfo("UnitTests.Atf.Dom.TestExtensionInfo");
            Assert.IsNotNull(getInfo);
            Assert.AreEqual(getInfo, extension);

            getInfo = domDerivedType.GetExtensionInfo("UnitTests.Atf.Dom.TestExtensionInfo");
            Assert.IsNotNull(getInfo);
            Assert.AreEqual(getInfo, extension);
            
            ExtensionInfo anotherGetInfo = domDerivedType.GetExtensionInfo("UnitTests.Atf.Dom.AnotherName.TestExtensionInfo");
            Assert.IsNotNull(anotherGetInfo);
            Assert.AreEqual(anotherGetInfo, anotherExtension);
        }
Beispiel #18
0
        private void AddNewLayer()
        {
            object lastHit = m_layerLister.LastHit;
            ILayer newLayer = new DomNode(Schema.layerType.Type).As<ILayer>();
            newLayer.Name = "New Layer".Localize();

            IList<ILayer> layerList = null;
            var layer = lastHit.As<ILayer>();
            if (layer != null)
            {
                layerList = layer.Layers;
            }
            else
            {
                LayeringContext layeringContext = m_layerLister.TreeView.As<LayeringContext>();
                    if (layeringContext != null)
                        layerList = layeringContext.Layers;
            }
            if (layerList != null)
            {
                var transactionContext = m_layerLister.TreeView.As<ITransactionContext>();
                transactionContext.DoTransaction(
                    delegate
                    {
                        layerList.Add(newLayer);
                    },
                    m_addLayer.Text);
            }
        }
Beispiel #19
0
        // Filter out sub-circuits that are not actually needed
        protected override void WriteElement(DomNode node, XmlWriter writer)
        {
            var subCircuit = node.As<SubCircuit>();
            if (subCircuit != null && !m_usedSubCircuits.Contains(subCircuit))
                return;

            base.WriteElement(node, writer);
        }
Beispiel #20
0
        /// <summary>
        /// Constructor with property and DomNode</summary>
        /// <param name="property">The matching property</param>
        /// <param name="domNode">The DomNode with the matching property</param>
        public DomNodePropertyMatch(PropertyDescriptor property, DomNode domNode)
        {
            if (property == null || domNode == null)
                throw new ArgumentNullException("Cannot create a DomNodePropertyMatchCandiate without valid non-null arguments");

            m_propertyDescriptor = property;
            m_domNode = domNode;
        }
        /// <summary>
        /// Returns a sequence of node-attribute pairs for all references to target</summary>
        /// <param name="target">Reference target</param>
        /// <returns>Sequence of node-attribute pairs for all references to target</returns>
        public IEnumerable<Pair<DomNode, AttributeInfo>> GetReferences(DomNode target)
        {
            List<Pair<DomNode, AttributeInfo>> references;
            if (m_nodeReferenceLists.TryGetValue(target, out references))
                return references;

            return EmptyEnumerable<Pair<DomNode, AttributeInfo>>.Instance;
        }
Beispiel #22
0
        public Slot(DomNode owner, ChildInfo childInfo)
        {
            if (owner == null || childInfo == null)
                throw new ArgumentNullException();

            m_owner = owner;
            m_childInfo = childInfo;
        }
Beispiel #23
0
 private static DomNode CreateArmor(string name, int defense, int price)
 {
     var armor = new DomNode(Schema.armorType.Type);
     armor.SetAttribute(Schema.armorType.nameAttribute, name);
     armor.SetAttribute(Schema.armorType.defenseAttribute, defense);
     armor.SetAttribute(Schema.armorType.priceAttribute, price);
     return armor;
 }
Beispiel #24
0
 private static DomNode CreateClub(bool hasSpikes, int damage, float weight)
 {
     var club = new DomNode(Schema.clubType.Type);
     club.SetAttribute(Schema.clubType.spikesAttribute, hasSpikes);
     club.SetAttribute(Schema.clubType.DamageAttribute, damage);
     club.SetAttribute(Schema.clubType.wieghtAttribute, weight);
     return club;
 }
Beispiel #25
0
 public void TestConstructor()
 {
     DomNodeType type = new DomNodeType("child");
     ChildInfo info = new ChildInfo("test", type);
     DomNode test = new DomNode(type, info);
     Assert.AreSame(test.Type, type);
     Assert.AreSame(test.ChildInfo, info);
 }
Beispiel #26
0
 protected DomNode CreateTree()
 {
     DomNode root = new DomNode(RootType);
     DomNode child = new DomNode(ChildType);
     DomNode grandchild = new DomNode(ChildType);
     child.SetChild(ChildInfo, grandchild);
     root.SetChild(ChildInfo, child);
     return root;
 }
Beispiel #27
0
 /// <summary>
 /// Writes the node tree to a stream, using default settings for the XmlWriter</summary>
 /// <param name="root">Node tree to write</param>
 /// <param name="stream">Write stream</param>
 /// <param name="uri">URI of stream</param>
 public virtual void Write(DomNode root, Stream stream, Uri uri)
 {
     XmlWriterSettings settings = new XmlWriterSettings();
     settings.Indent = true;
     settings.IndentChars = "\t";
     settings.NewLineHandling = NewLineHandling.Replace;
     settings.NewLineChars = "\r\n";
     Write(root, stream, uri, settings);
 }
 public override void AddChild(DomNode childNode)
 {
     //add dom node to this node
     if (childNode.ParentNode != null)
     {
         throw new NotSupportedException("remove from its parent first");
     }
     shadowDoc.RootNode.AddChild(childNode);
 }
Beispiel #29
0
        // Scan for all sub-circuits that are referenced directly or indirectly by a module in
        //  the root of the document
        public override void Write(DomNode root, Stream stream, Uri uri)
        {
            m_usedSubCircuits = new HashSet<Sce.Atf.Controls.Adaptable.Graphs.SubCircuit>();

            foreach (var module in root.Cast<Circuit>().Elements)
                FindUsedSubCircuits(module.DomNode);

            base.Write(root, stream, uri);
        }
 /// <inheritdoc/>
 public ResolveVisitorNavigationMode Scan(DomNode node)
 {
     ResolveVisitorNavigationMode mode;
     if (dict.TryGetValue(node, out mode)) {
         return mode;
     } else {
         return ResolveVisitorNavigationMode.Skip;
     }
 }
Beispiel #31
0
            public override object GetValue(object component)
            {
                try
                {
                    if (m_font == null)
                    {
                        DomNode   param     = m_domObject.GetChild(SkinSchema.valueInfoType.constructorParamsChild);
                        string    fname     = null;
                        float     fontSize  = 1.0f;
                        FontStyle fontStyle = FontStyle.Regular;

                        foreach (var arg in param.GetChildren(SkinSchema.constructorParamsType.valueInfoChild))
                        {
                            string typeName = (string)arg.GetAttribute(SkinSchema.valueInfoType.typeAttribute);
                            Type   type     = SkinUtil.GetType(typeName);
                            string val      = (string)arg.GetAttribute(SkinSchema.valueInfoType.valueAttribute);

                            if (type == typeof(string))
                            {
                                fname = val;
                            }
                            else if (type == typeof(float))
                            {
                                fontSize = float.Parse(val);
                            }
                            else if (type == typeof(FontStyle))
                            {
                                fontStyle = (FontStyle)Enum.Parse(typeof(FontStyle), val);
                            }
                        }
                        m_font = new Font(fname, fontSize, fontStyle);
                    }
                }
                catch { } // suppress parsing error.

                return(m_font);
            }
Beispiel #32
0
        private void Init()
        {
            if (m_game != null)
            {
                return;
            }

            NativeObjectAdapter curLevel = GameEngine.GetGameLevel();

            try
            {
                // create new document by creating a Dom node of the root type defined by the schema
                DomNode   rootNode = new DomNode(m_schemaLoader.GameType, m_schemaLoader.GameRootElement);
                INameable nameable = rootNode.As <INameable>();
                nameable.Name = "Game";
                NativeObjectAdapter gameLevel = rootNode.Cast <NativeObjectAdapter>();
                GameEngine.CreateObject(gameLevel);
                GameEngine.SetGameLevel(gameLevel);
                gameLevel.UpdateNativeOjbect();
                NativeGameWorldAdapter gworld = rootNode.Cast <NativeGameWorldAdapter>();
                m_game = rootNode.Cast <IGame>();
                IGameObjectFolder rootFolder = m_game.RootGameObjectFolder;
                m_renderSurface.Game            = m_game;
                m_renderSurface.GameEngineProxy = m_gameEngine;
            }
            finally
            {
                GameEngine.SetGameLevel(curLevel);
            }


            m_mainWindow.Closed += delegate
            {
                GameEngine.DestroyObject(m_game.Cast <NativeObjectAdapter>());
                m_renderSurface.Dispose();
            };
        }
Beispiel #33
0
        public static IAdaptable Create()
        {
            var node = new DomNode(Schema.triMeshMarkerType.Type);

            if (node == null)
            {
                return(null);
            }

            var result = node.As <TriMeshMarker>();

            if (result == null)
            {
                return(null);
            }

            result.AddPoint(new Vec3F(-100.0f, -100.0f, 0.0f));
            result.AddPoint(new Vec3F(100.0f, -100.0f, 0.0f));
            result.AddPoint(new Vec3F(-100.0f, 100.0f, 0.0f));
            result.AddPoint(new Vec3F(100.0f, 100.0f, 0.0f));
            result.IndexList = new int[] { 0, 1, 2, 2, 1, 3 };
            // node.InitializeExtensions();
            return(result);
        }
Beispiel #34
0
        /// <summary>
        /// Creates a reference instance that references the specified target item</summary>
        /// <param name="item">Item to create reference for</param>
        public override object CreateReference(object item)
        {
            var template = item.Cast <ScriptTemplate>();

            if (template.Target.Is <ScriptGroup>())
            {
                var groupReference = new DomNode(groupTemplateRefType.Type).Cast <ScriptGroupReference>();
                groupReference.Template         = template;
                groupReference.Id               = template.Name;
                groupReference.TitleText        = template.Name;
                groupReference.Group.SourceGuid = template.Guid;
                return(groupReference);
            }
            if (template.Target.Is <ScriptNode>())
            {
                var moduleReference = new DomNode(moduleTemplateRefType.Type).Cast <ScriptNodeReference>();
                moduleReference.Template           = template;
                moduleReference.Id                 = template.Name;
                moduleReference.TitleText          = template.Name;
                moduleReference.Element.SourceGuid = template.Guid;
                return(moduleReference);
            }
            return(null);
        }
Beispiel #35
0
        /// <summary>
        /// Creates a reference instance that references the specified target item</summary>
        /// <param name="item">Item to create reference for</param>
        public override object CreateReference(object item)
        {
            var template = item.Cast <Template>();

            if (template.Target.Is <Group>())
            {
                var groupReference = new DomNode(Schema.groupTemplateRefType.Type).Cast <GroupInstance>();
                groupReference.SourceGuid = template.Guid;
                groupReference.Template   = template;
                groupReference.Id         = template.Name;
                groupReference.Name       = template.Name;
                return(groupReference);
            }
            if (template.Target.Is <Module>())
            {
                var moduleReference = new DomNode(Schema.moduleTemplateRefType.Type).Cast <ModuleInstance>();
                moduleReference.SourceGuid = template.Guid;
                moduleReference.Template   = template;
                moduleReference.Id         = template.Name;
                moduleReference.Name       = template.Name;
                return(moduleReference);
            }
            return(null);
        }
Beispiel #36
0
        public void TestDuplicateExtensionInfo()
        {
            var ext1 = new ExtensionInfo <TestAdapter1>("foo");
            var ext2 = new ExtensionInfo <TestAdapter2>("foo");

            var domType = new DomNodeType(
                "test",
                null,
                EmptyEnumerable <AttributeInfo> .Instance,
                EmptyEnumerable <ChildInfo> .Instance,
                new ExtensionInfo[] { ext1, ext2 });

            var domNode = new DomNode(domType);

            object resultExt1 = domNode.GetExtension(ext1);
            object resultExt2 = domNode.GetExtension(ext2);

            Assert.IsTrue(resultExt1 is TestAdapter1);
            Assert.IsTrue(resultExt2 is TestAdapter2);

            object[] decorators = domNode.GetDecorators(typeof(object)).ToArray();
            Assert.IsTrue(
                decorators.Length == 2 &&
                decorators[0] == resultExt1 &&
                decorators[1] == resultExt2);

            DomNodeAdapter[] extensions = domNode.AsAll <DomNodeAdapter>().ToArray();
            Assert.IsTrue(
                extensions.Length == 2 &&
                extensions[0] == resultExt1 &&
                extensions[1] == resultExt2);

            // Searching by name is a problem, though. The search is ambiguous.
            // See tracker item for discussion: http://tracker.ship.scea.com/jira/browse/WWSATF-522
            Assert.Throws <InvalidOperationException>(() => domType.GetExtensionInfo("foo"));
        }
            public IEnumerable <object> GetChildren(object parent)
            {
                DomNode node = parent as DomNode;

                if (node != null)
                {
                    if (m_showAdapters)
                    {
                        // get all adapters, and wrap so that the TreeControlAdapter doesn't confuse
                        //  them with their parent DomNode; remember that the DomNode and its adapters
                        //  are logically Equal.
                        IEnumerable <DomNodeAdapter> adapters = node.AsAll <DomNodeAdapter>();
                        foreach (DomNodeAdapter adapter in adapters)
                        {
                            yield return(new Adapter(adapter));
                        }
                    }
                    // get child Dom objects
                    foreach (DomNode child in node.Children)
                    {
                        yield return(child);
                    }
                }
            }
            public void GetInfo(object item, ItemInfo info)
            {
                info.IsLeaf = !HasChildren(item);

                DomNode node = item as DomNode;

                if (node != null && node.ChildInfo != null)
                {
                    info.Label = node.ChildInfo.Name;
                    //info.ImageIndex = info.GetImageList().Images.IndexOfKey(Resources.DomObjectImage);
                    return;
                }

                Adapter adapter = item as Adapter;

                if (adapter != null)
                {
                    DomNodeAdapter nodeAdapter = adapter.Adaptee as DomNodeAdapter;
                    StringBuilder  sb          = new StringBuilder();

                    Type type = nodeAdapter.GetType();
                    sb.Append(type.Name);
                    sb.Append(" (");
                    foreach (Type interfaceType in type.GetInterfaces())
                    {
                        sb.Append(interfaceType.Name);
                        sb.Append(",");
                    }
                    sb[sb.Length - 1] = ')'; // remove trailing comma

                    info.Label = sb.ToString();
                    //info.ImageIndex = info.GetImageList().Images.IndexOfKey(Resources.DomObjectInterfaceImage);

                    return;
                }
            }
Beispiel #39
0
        /// <summary>
        /// Inserts 'item' into the set of objects at the desired position. Can only be called
        /// if CanInsert() returns true.</summary>
        /// <param name="parent">The object that will become the parent of the inserted object.
        /// Can be null if the list of objects is a flat list or if the root should be replaced.</param>
        /// <param name="before">The object that is immediately before the inserted object.
        /// Can be null to indicate that the inserted item should become the first child.</param>
        /// <param name="item">The item to be inserted. Consider using Util.ConvertData(item, false)
        /// to retrieve the final one or more items to be inserted.</param>
        void IOrderedInsertionContext.Insert(object parent, object before, object item)
        {
            DomNode parentDom = parent as DomNode;
            DomNode beforeDom = before as DomNode;

            DomNode[] itemsDom = _GetDomNodes(item);

            ChildInfo       childInfo = parentDom.Type.GetChildInfo("node");
            IList <DomNode> childList = parentDom.GetChildList(childInfo);

            if (before == null)
            {
                int index = 0;
                foreach (DomNode node in itemsDom)
                {
                    childList.Insert(++index, node);
                }
            }

            int beforeIndex = childList.IndexOf(beforeDom);

            if (beforeIndex == childList.Count - 1)
            {
                foreach (DomNode node in itemsDom)
                {
                    childList.Add(node);
                }
            }
            else
            {
                foreach (DomNode node in itemsDom)
                {
                    childList.Insert(++beforeIndex, node);
                }
            }
        }
        private void SelectAllInstances()
        {
            DomNodeType domNodeType = SelectedNodeType;

            if (domNodeType == null)
            {
                return;
            }

            ISelectionContext selectionContext = SelectionContext;

            if (selectionContext == null)
            {
                return;
            }

            DomNode rootNode = GetRootNode(selectionContext);

            if (rootNode == null)
            {
                return;
            }


            selectionContext.Clear();
            List <Path <object> > newSelection = new List <Path <object> >();

            foreach (DomNode domNode in GetNodesOfType(rootNode, domNodeType))
            {
                newSelection.Add(Util.AdaptDomPath(domNode));
            }
            if (newSelection.Count > 0)
            {
                selectionContext.SetRange(newSelection);
            }
        }
Beispiel #41
0
        public void TestCopy_MultipleNodes()
        {
            DomNodeType type     = new DomNodeType("type");
            ChildInfo   info     = new ChildInfo("child", type);
            ChildInfo   infoList = new ChildInfo("childList", type, true);

            type.Define(info);
            type.Define(infoList);
            ChildInfo rootInfo = new ChildInfo("root", type, true);
            DomNode   test     = new DomNode(type, rootInfo);
            DomNode   child1   = new DomNode(type);

            test.SetChild(info, child1);
            DomNode         child2 = new DomNode(type);
            DomNode         child3 = new DomNode(type);
            IList <DomNode> list   = test.GetChildList(infoList);

            list.Add(child2);
            list.Add(child3);

            DomNode[] result = DomNode.Copy(new DomNode[] { test });
            Assert.AreEqual(result.Length, 1);
            Assert.True(Equals(result[0], test));
        }
        // removes refs from the tracker, and reports removed external refs
        private void RemoveReference(DomNode owner, AttributeInfo attributeInfo, DomNode target)
        {
            List <Pair <DomNode, AttributeInfo> > referenceList;

            if (m_nodeReferenceLists.TryGetValue(target, out referenceList))
            {
                referenceList.Remove(new Pair <DomNode, AttributeInfo>(owner, attributeInfo));
                if (referenceList.Count == 0)
                {
                    m_nodeReferenceLists.Remove(target);
                }
            }

            // if target's root isn't the context's root, then it's an external reference
            //  that is being removed.
            DomNode targetRoot = target.GetRoot();

            if (DomNode != targetRoot)
            {
                ReferenceEventArgs e = new ReferenceEventArgs(owner, attributeInfo, target);
                OnExternalReferenceRemoved(e);
                ExternalReferenceRemoved.Raise(this, e);
            }
        }
Beispiel #43
0
        public IEnumerable <object> GetChildren(object parent)
        {
            DomNode domNode = parent.As <DomNode>();

            if (domNode != null)
            {
                GameReference gameRef = domNode.As <GameReference>();
                if (gameRef != null && gameRef.Target != null)
                {
                    domNode = gameRef.Target.As <DomNode>();
                }
                domNode = LevelEditorXLE.Patches.GetReferenceTarget(domNode);

                foreach (ChildInfo childInfo in domNode.Type.Children)
                {
                    // todo use schema annotatoin to mark types that need to have ref slot.
                    bool isReference = Schema.gameObjectReferenceType.Type.IsAssignableFrom(childInfo.Type) ||
                                       Schema.resourceReferenceType.Type.IsAssignableFrom(childInfo.Type) ||
                                       LevelEditorXLE.Patches.IsReferenceType(childInfo.Type);

                    bool hasChild = false;
                    foreach (DomNode child in domNode.GetChildren(childInfo))
                    {
                        hasChild = true;
                        if (child.Is <IListable>())
                        {
                            yield return(child);
                        }
                    }
                    if ((hasChild == false || childInfo.IsList) && isReference)
                    {
                        yield return(new Slot(domNode, childInfo));
                    }
                }
            }
        }
Beispiel #44
0
        /// <summary>
        /// Attempts to resolve (e.g., load from a file) the resource associated with the given URI</summary>
        /// <param name="uri">Resource URI</param>
        /// <returns>The resolved resource or null if there was a failure of some kind</returns>
        public IResource Resolve(Uri uri)
        {
            string fileName = PathUtil.GetCanonicalPath(uri);

            if (!fileName.EndsWith(".obj"))
            {
                return(null);
            }

            DomNode domNode = null;

            try
            {
                using (Stream stream = File.OpenRead(fileName))
                {
                    ObjFile.PopulateDomNode(stream, ref domNode, uri);
                }
            }
            catch (IOException e)
            {
                Outputs.WriteLine(OutputMessageType.Warning, "Could not load resource: " + e.Message);
            }

            IResource resource = null;

            if (domNode != null)
            {
                resource = domNode.As <IResource>();
                if (resource != null)
                {
                    resource.Uri = uri;
                }
            }

            return(resource);
        }
Beispiel #45
0
        private void LoadSavedVarFilters()
        {
            var varFilters =
                FindLuaVarFiltersElement(m_project);

            // Create variable filters
            if (varFilters == null)
            {
                var domNode =
                    new DomNode(SledLuaSchema.SledLuaVarFiltersType.Type);

                varFilters = domNode.As <SledLuaVarFiltersType>();
                m_project.UserSettings.Add(varFilters);
                SaveVarFilters(varFilters);
            }
            else
            {
                varFilters.Load(
                    m_globalVariableFilterState,
                    m_localVariableFilterState,
                    m_upvalueVariableFilterState,
                    m_envVarVariableFilterState);
            }
        }
Beispiel #46
0
        public void TestGetAttribute()
        {
            DomNodeType   type = new DomNodeType("child");
            AttributeInfo info = GetIntAttribute("int");

            type.Define(info);
            DomNode test = new DomNode(type);

            Assert.True(test.IsAttributeDefault(info));
            Assert.Null(test.GetLocalAttribute(info));

            test.SetAttribute(info, 2);
            Assert.AreEqual(test.GetAttribute(info), 2);
            Assert.AreEqual(test.GetLocalAttribute(info), 2);
            Assert.False(test.IsAttributeDefault(info));

            test.SetAttribute(info, null);
            Assert.True(test.IsAttributeDefault(info));
            Assert.Null(test.GetLocalAttribute(info));

            test.SetAttribute(info, 0);
            Assert.AreEqual(test.GetAttribute(info), 0);
            Assert.True(test.IsAttributeDefault(info));
        }
Beispiel #47
0
        /// <summary>
        /// Writes the node tree to a stream</summary>
        /// <param name="root">Node tree to write</param>
        /// <param name="stream">Write stream</param>
        /// <param name="uri">URI of stream</param>
        /// <param name="settings">Settings for creating an XmlWriter. Specifies encoding, indent, etc.</param>
        public virtual void Write(DomNode root, Stream stream, Uri uri, XmlWriterSettings settings)
        {
            try
            {
                m_uri            = uri;
                m_root           = root;
                m_inlinePrefixes = new Dictionary <string, string>();

                using (XmlWriter writer = XmlWriter.Create(stream, settings))
                {
                    writer.WriteStartDocument();

                    WriteElement(root, writer);

                    writer.WriteEndDocument();
                }
            }
            finally
            {
                m_uri            = null;
                m_root           = null;
                m_inlinePrefixes = null;
            }
        }
Beispiel #48
0
        /// <summary>
        /// Copy all children from 'source' to 'dest', within the context of the specified page.
        /// </summary>
        /// <param name="page">the page which the nodes belong to</param>
        /// <param name="source">the node to copy from</param>
        /// <param name="dest">the node to copy to</param>
        /// <param name="handleXHTMLAsHTML">if true elements from the XHTML namespace are handled as HTML elements instead of DOM elements</param>
        private static void Copy(SgmlPage page, XmlNode source, DomNode dest, bool handleXHTMLAsHTML)
        {
            XmlNodeList nodeChildren = source.ChildNodes;

            for (int i = 0; i < nodeChildren.Count; i++)
            {
                XmlNode child = nodeChildren.Item(i);
                switch (child.NodeType)
                {
                case XmlNodeType.Element:
                    DomNode childXml = CreateFrom(page, child, handleXHTMLAsHTML);
                    dest.appendChild(childXml);
                    Copy(page, child, childXml, handleXHTMLAsHTML);
                    break;

                case XmlNodeType.Text:
                    dest.appendChild(new DomText(page, child.Value));
                    break;

                case XmlNodeType.CDATA:
                    dest.appendChild(new DomCDataSection(page, child.Value));
                    break;

                case XmlNodeType.Comment:
                    dest.appendChild(new DomComment(page, child.Value));
                    break;

                case XmlNodeType.ProcessingInstruction:
                    dest.appendChild(new DomProcessingInstruction(page, child.Name, child.Value));
                    break;

                default:
                    LOG.Warn("NodeType " + child.NodeType + " (" + child.Name + ") is not yet supported.");
                }
            }
        }
Beispiel #49
0
        /// <summary>
        /// Creates template folder</summary>
        /// <returns>TemplateFolder object</returns>
        protected virtual TemplateFolder CreateTemplateFolder()
        {
            var newFolder = new DomNode(TemplateFolderType).As <TemplateFolder>();

            newFolder.Name = "New Template Folder".Localize();

            var parentFolder = m_targetRef.Target.As <TemplateFolder>();

            if (parentFolder == null)
            {
                var templatinContext = m_targetRef.Target.As <TemplatingContext>();
                if (templatinContext != null)
                {
                    parentFolder = templatinContext.RootFolder;
                }
            }

            if (parentFolder != null)
            {
                parentFolder.Folders.Add(newFolder);
            }

            return(newFolder);
        }
Beispiel #50
0
            public void Load(string fileName, DomNode node)
            {
                foreach (DomNode child in node)
                {
                    switch (child.Name.ToLower())
                    {
                    case "menu-background": Background = UIDefaults.LoadBackground(fileName, child); break;

                    case "menu-border": Border = UIDefaults.LoadBorder(fileName, child); break;

                    case "menu-padding": MenuPadding.Load(fileName, child); break;

                    case "item-padding": ItemPadding.Load(fileName, child); break;

                    case "item-spacing": ItemSpacing.Load(fileName, child); break;

                    case "separator": Separator = UIDefaults.LoadBackground(fileName, child); break;

                    case "item-states": ItemStates.Load(fileName, child); break;

                    case "font": Font = UIDefaults.LoadFont(fileName, child); break;
                    }
                }
            }
Beispiel #51
0
        public static void CreateDefaultNodes(DomNode gameRoot)
        {
            var ext = gameRoot.As <Game.GameExtensions>();

            if (ext != null)
            {
                // Add default environment settings
                var envFolder = ext.EnvSettingsFolder;
                if (envFolder.Settings.Count == 0)
                {
                    envFolder.AddChild(Environment.XLEEnvSettings.Create(envFolder.GetNameForNewChild()));
                }

                // Add placements folder with an unnamed default placement document
                if (ext.PlacementsFolder == null)
                {
                    var newNode = Placements.PlacementsFolder.CreateStarter();
                    if (newNode != null)
                    {
                        ext.PlacementsFolder = newNode.As <Placements.PlacementsFolder>();
                    }
                }
            }
        }
        /// <summary>
        /// Converts the palette item into an object that can be inserted into an
        /// IInstancingContext</summary>
        /// <param name="item">Item to convert</param>
        /// <returns>Object that can be inserted into an IInstancingContext</returns>
        object IPaletteClient.Convert(object item)
        {
            DomNodeType nodeType = (DomNodeType)item;
            DomNode     node     = new DomNode(nodeType);

            NodeTypePaletteItem paletteItem = nodeType.GetTag <NodeTypePaletteItem>();

            if (paletteItem != null)
            {
                if (nodeType.IdAttribute != null)
                {
                    node.SetAttribute(nodeType.IdAttribute, paletteItem.Name); // unique id, for referencing
                }
                if (nodeType == DomTypes.eventType.Type)
                {
                    node.SetAttribute(DomTypes.eventType.nameAttribute, paletteItem.Name);
                }
                else if (DomTypes.resourceType.Type.IsAssignableFrom(nodeType))
                {
                    node.SetAttribute(DomTypes.resourceType.nameAttribute, paletteItem.Name);
                }
            }
            return(node);
        }
Beispiel #53
0
        public IControlPoint InsertPoint(uint index, float x, float y, float z)
        {
            IControlPoint cpt               = CreateControlPoint();
            int           numSteps          = GetAttribute <int>(Schema.curveType.stepsAttribute);
            int           interpolationType = GetAttribute <int>(Schema.curveType.interpolationTypeAttribute);

            if (interpolationType != 0 && numSteps > 0)
            {
                index = index / (uint)numSteps;
            }


            Path <DomNode> path         = new Path <DomNode>(DomNode.GetPath());
            Matrix4F       toworld      = TransformUtils.CalcPathTransform(path, path.Count - 1);
            Matrix4F       worldToLocal = new Matrix4F();

            worldToLocal.Invert(toworld);
            Vec3F pos = new Vec3F(x, y, z);

            worldToLocal.Transform(ref pos);
            cpt.Translation = pos;
            ControlPoints.Insert((int)index + 1, cpt);
            return(cpt);
        }
Beispiel #54
0
        private void Init()
        {
            NativeObjectAdapter curLevel = GameEngine.GetGameLevel();

            try
            {
                // create new document by creating a Dom node of the root type defined by the schema
                DomNode   rootNode = new DomNode(m_schemaLoader.GameType, m_schemaLoader.GameRootElement);
                INameable nameable = rootNode.Cast <INameable>();
                nameable.Name = "ThumbnailGenerator";

                NativeObjectAdapter gameLevel = rootNode.Cast <NativeObjectAdapter>();
                GameEngine.CreateObject(gameLevel);
                GameEngine.SetGameLevel(gameLevel);
                gameLevel.UpdateNativeOjbect();
                NativeGameWorldAdapter gworld = rootNode.Cast <NativeGameWorldAdapter>();

                m_game = rootNode.Cast <IGame>();
                IGameObjectFolder rootFolder = m_game.RootGameObjectFolder;
                m_renderSurface          = new TextureRenderSurface(96, 96);
                m_renderState            = new RenderState();
                m_renderState.RenderFlag = GlobalRenderFlags.Solid | GlobalRenderFlags.Textured | GlobalRenderFlags.Lit | GlobalRenderFlags.Shadows;
            }
            finally
            {
                GameEngine.SetGameLevel(curLevel);
            }


            m_mainWindow.Closed += delegate
            {
                GameEngine.DestroyObject(m_game.Cast <NativeObjectAdapter>());
                m_renderSurface.Dispose();
                m_renderState.Dispose();
            };
        }
Beispiel #55
0
            /// <summary>
            /// Run the copier
            /// </summary>
            /// <param name="domProjectTree">Tree to copy</param>
            /// <param name="domTempTree">Copied tree</param>
            public void Run(DomNode domProjectTree, DomNode domTempTree)
            {
                var lstProjFolders = new List <SledProjectFilesFolderType>();

                GatherNodeTypes(domProjectTree, lstProjFolders);

                var lstTempFolders = new List <SledProjectFilesFolderType>();

                GatherNodeTypes(domTempTree, lstTempFolders);

                var lstPairs = new List <Pair <SledProjectFilesFolderType, SledProjectFilesFolderType> >();

                foreach (var projFolder in lstProjFolders)
                {
                    foreach (var tempFolder in lstTempFolders)
                    {
                        if ((projFolder.Files.Count == tempFolder.Files.Count) &&
                            (projFolder.Folders.Count == tempFolder.Folders.Count) &&
                            (string.Compare(projFolder.Name, tempFolder.Name, StringComparison.Ordinal) == 0))
                        {
                            lstPairs.Add(new Pair <SledProjectFilesFolderType, SledProjectFilesFolderType>(projFolder, tempFolder));
                            break;
                        }
                    }
                }

                if (lstPairs.Count <= 0)
                {
                    return;
                }

                foreach (var pair in lstPairs)
                {
                    SyncNameAndExpanded(pair.First, pair.Second);
                }
            }
Beispiel #56
0
        /// <summary>
        /// Gets the lineage of this object, starting with the object, and ending with
        /// the root object.</summary>
        public static IEnumerable <DomNode> Lineage(object obj)
        {
            Path <object> path = obj as Path <object>;

            if (path != null)
            {
                for (int index = path.Count - 1; index >= 0; index--)
                {
                    DomNode node = path[index] as DomNode;
                    if (node != null)
                    {
                        yield return(node);
                    }
                }
            }
            else
            {
                DomNode node = obj as DomNode;
                foreach (DomNode childNode in node.Lineage)
                {
                    yield return(childNode);
                }
            }
        }
Beispiel #57
0
 private static bool IsPrototypeItem(DomNode child, DomNode parent)
 {
     return
         (child.Is <PrototypeFolder>() ||
          (parent != null && parent.Is <PrototypeFolder>()));
 }
Beispiel #58
0
        /// <summary>
        /// Loads the document at the given URI. Creates a D2dTimelineRenderer and D2dTimelineControl
        /// (through TimelineDocument's Renderer property) to render and display timelines.
        /// If isMasterDocument is true and if the file doesn't exist, a new document is created.</summary>
        /// <param name="uri">URI of document to load</param>
        /// <param name="isMasterDocument">True iff is master document</param>
        /// <returns>TimelineDocument loaded</returns>
        private TimelineDocument LoadOrCreateDocument(Uri uri, bool isMasterDocument)
        {
            // Documents need to have a absolute Uri, so that the relative references to sub-documents
            //  are not ambiguous, and so that the FileWatcherService can be used.
            string filePath;

            if (uri.IsAbsoluteUri)
            {
                filePath = uri.LocalPath;
            }
            else if (!isMasterDocument)
            {
                filePath = PathUtil.GetAbsolutePath(uri.OriginalString,
                                                    Path.GetDirectoryName(s_repository.ActiveDocument.Uri.LocalPath));
                uri = new Uri(filePath, UriKind.Absolute);
            }
            else
            {
                filePath = PathUtil.GetAbsolutePath(uri.OriginalString, Directory.GetCurrentDirectory());
                uri      = new Uri(filePath, UriKind.Absolute);
            }

            // Check if the repository contains this Uri. Remember that document Uris have to be absolute.
            bool             isNewToThisEditor = true;
            DomNode          node     = null;
            TimelineDocument document = (TimelineDocument)s_repository.GetDocument(uri);

            if (document != null)
            {
                node = document.DomNode;
                isNewToThisEditor = false;
            }
            else if (File.Exists(filePath))
            {
                // read existing document using standard XML reader
                using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    DomXmlReader reader = new DomXmlReader(s_schemaLoader);
                    node = reader.Read(stream, uri);
                }
            }
            else if (isMasterDocument)
            {
                // create new document by creating a Dom node of the root type defined by the schema
                node = new DomNode(Schema.timelineType.Type, Schema.timelineRootElement);
            }

            if (node != null)
            {
                if (document == null)
                {
                    document = node.Cast <TimelineDocument>();

                    D2dTimelineRenderer renderer = CreateTimelineRenderer();
                    document.Renderer = renderer;
                    renderer.Init(document.TimelineControl.D2dGraphics);

                    string      fileName    = Path.GetFileName(filePath);
                    ControlInfo controlInfo = new ControlInfo(fileName, filePath, StandardControlGroup.Center);

                    //Set IsDocument to true to prevent exception in command service if two files with the
                    //  same name, but in different directories, are opened.
                    controlInfo.IsDocument = true;

                    TimelineContext timelineContext = document.Cast <TimelineContext>();
                    timelineContext.ControlInfo = controlInfo;

                    document.Uri = uri;

                    if (isMasterDocument)
                    {
                        s_repository.ActiveDocument = document;//adds 'document'
                    }
                    else
                    {
                        // For sub-documents, we want ActiveDocument to remain the main document so that
                        //  TimelineValidator can identify if a sub-document or master document is being
                        //  modified.
                        IDocument previous = s_repository.ActiveDocument;
                        s_repository.ActiveDocument = document; //adds 'document'
                        s_repository.ActiveDocument = previous; //restores master document
                    }
                }

                IHierarchicalTimeline hierarchical = document.Timeline as IHierarchicalTimeline;
                if (hierarchical != null)
                {
                    ResolveAll(hierarchical, new HashSet <IHierarchicalTimeline>());
                }

                // Listen to events if this is the first time we've seen this.
                if (isNewToThisEditor)
                {
                    // The master document/context needs to listen to events on any sub-document
                    //  so that transactions can be cancelled correctly.
                    if (isMasterDocument)
                    {
                        node.AttributeChanging += DomNode_AttributeChanging;
                    }
                    else
                    {
                        DomNode masterNode = s_repository.ActiveDocument.As <DomNode>();
                        node.SubscribeToEvents(masterNode);
                    }
                }

                // Initialize Dom extensions now that the data is complete
                node.InitializeExtensions();
            }

            return(document);
        }
Beispiel #59
0
        protected override IList <object> Pick(MouseEventArgs e)
        {
            bool          multiSelect = DragOverThreshold;
            List <object> paths       = new List <object>();

            Picking.HitRecord[] hits;

            if (multiSelect)
            {// frustum pick
                RectangleF rect    = MakeRect(FirstMousePoint, CurrentMousePoint);
                var        frustum = XLEBridgeUtils.Utils.MakeFrustumMatrix(Utils.AsCameraDesc(Camera), rect, ClientSize);
                hits = Picking.FrustumPick(
                    GameEngine.GetEngineDevice(),
                    Adapter.SceneManager, Adapter.TechniqueContext,
                    frustum, Utils.AsCameraDesc(Camera), ClientSize,
                    Picking.Flags.Objects | Picking.Flags.Helpers);
            }
            else
            {// ray pick
                Ray3F rayW = GetWorldRay(CurrentMousePoint);
                hits = Picking.RayPick(
                    GameEngine.GetEngineDevice(),
                    Adapter.SceneManager, Adapter.TechniqueContext,
                    rayW, Utils.AsCameraDesc(Camera), ClientSize,
                    Picking.Flags.Terrain | Picking.Flags.Objects | Picking.Flags.Helpers);
            }

            if (hits == null)
            {
                return(new List <object>());
            }

            // create unique list of hits
            HashSet <ulong> instanceSet = new HashSet <ulong>();
            var             uniqueHits  = new List <Picking.HitRecord>();

            // build 'path' objects for each hit record.
            foreach (var hit in hits)
            {
                bool added = instanceSet.Add(hit.instanceId);
                if (added)
                {
                    uniqueHits.Add(hit);
                }
            }

            var firstHit = new Picking.HitRecord();


            // build 'path' objects for each hit record.
            foreach (var hit in uniqueHits)
            {
                var nativeIdMapping = Globals.MEFContainer.GetExportedValue <INativeIdMapping>();
                var nobj            = nativeIdMapping.GetAdapter(hit.documentId, hit.instanceId).As <DomNodeAdapter>();
                if (nobj == null)
                {
                    continue;
                }

                DomNode dom     = nobj.DomNode;
                object  hitPath = Util.AdaptDomPath(dom);
                object  obj     = DesignView.PickFilter.Filter(hitPath, e);
                if (obj != null)
                {
                    if (paths.Count == 0)
                    {
                        firstHit = hit;
                    }
                    var newPath = obj as AdaptablePath <object> ?? Util.AdaptDomPath((DomNode)obj);
                    paths.Add(newPath);
                }
            }


            if (multiSelect == false && paths.Count > 0)
            {
                var path = paths[0];
                ISelectionContext selection = DesignView.Context.As <ISelectionContext>();
                ILinear           linear    = path.As <ILinear>();
                if (linear != null &&
                    Control.ModifierKeys == System.Windows.Forms.Keys.Shift &&
                    selection.SelectionContains(path))
                {
                    ITransactionContext trans = DesignView.Context.As <ITransactionContext>();
                    trans.DoTransaction(
                        delegate
                    {
                        linear.InsertPoint(firstHit.index, firstHit.hitPt.X, firstHit.hitPt.Y, firstHit.hitPt.Z);
                    }, "insert control point".Localize()
                        );
                }
            }
            return(paths);
        }
Beispiel #60
0
 private static bool IsStatechartItem(DomNode child, DomNode parent)
 {
     return
         (parent != null && parent.GetRoot().Is <Statechart>());
 }