Example #1
0
        public void TestChildRemoveEvents()
        {
            DomNodeType type     = new DomNodeType("type");
            ChildInfo   info     = new ChildInfo("child", type);
            ChildInfo   infoList = new ChildInfo("childList", type, true);

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

            test.ChildRemoving += new EventHandler <ChildEventArgs>(test_ChildRemoving);
            test.ChildRemoved  += new EventHandler <ChildEventArgs>(test_ChildRemoved);

            // test child
            DomNode child = new DomNode(type);

            test.SetChild(info, child);
            ChildRemovingArgs = null;
            ChildRemovedArgs  = null;
            test.SetChild(info, null);
            ChildEventArgs expected = new ChildEventArgs(test, info, child, 0);

            Assert.True(Equals(ChildRemovingArgs, expected));
            Assert.True(Equals(ChildRemovedArgs, expected));

            // test inserting a child when there is one there already
            test.SetChild(info, child);
            DomNode newChild = new DomNode(type);

            ChildRemovingArgs = null;
            ChildRemovedArgs  = null;
            test.SetChild(info, newChild);
            expected = new ChildEventArgs(test, info, child, 0);
            Assert.True(Equals(ChildRemovingArgs, expected));
            Assert.True(Equals(ChildRemovedArgs, expected));

            // test child list
            IList <DomNode> list   = test.GetChildList(infoList);
            DomNode         child2 = new DomNode(type);

            list.Add(child2);
            DomNode child3 = new DomNode(type);

            list.Add(child3);
            ChildRemovingArgs = null;
            ChildRemovedArgs  = null;
            list.Remove(child3);
            expected = new ChildEventArgs(test, infoList, child3, 1);
            Assert.True(Equals(ChildRemovingArgs, expected));
            Assert.True(Equals(ChildRemovedArgs, expected));
            ChildRemovingArgs = null;
            ChildRemovedArgs  = null;
            list.Remove(child2);
            expected = new ChildEventArgs(test, infoList, child2, 0);
            Assert.True(Equals(ChildRemovingArgs, expected));
            Assert.True(Equals(ChildRemovedArgs, expected));
        }
Example #2
0
 public void TestOnChildRemoved()
 {
     DomNode root = new DomNode(m_rootType);
     Validator validator = root.As<Validator>();
     DomNode child = new DomNode(m_childType);
     root.SetChild(m_childInfo, child);
     root.SetChild(m_childInfo, null);
     Assert.AreSame(validator.Sender, root);
     ChildEventArgs e = (ChildEventArgs)validator.E;
     Assert.NotNull(e);
     Assert.AreSame(e.Parent, root);
 }
Example #3
0
        public void TestOnChildRemoved()
        {
            DomNode   root      = new DomNode(m_rootType);
            Validator validator = root.As <Validator>();
            DomNode   child     = new DomNode(m_childType);

            root.SetChild(m_childInfo, child);
            root.SetChild(m_childInfo, null);
            Assert.AreSame(validator.Sender, root);
            ChildEventArgs e = (ChildEventArgs)validator.E;

            Assert.NotNull(e);
            Assert.AreSame(e.Parent, root);
        }
Example #4
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));

            DomNode singleResult = DomNode.Copy(test);

            Assert.True(Equals(singleResult, test));
        }
Example #5
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;
 }
Example #6
0
 private DomNode CreateTree()
 {
     DomNode root = new DomNode(m_rootType);
     DomNode child = new DomNode(m_childType);
     DomNode grandchild = new DomNode(m_childType);
     child.SetChild(m_childInfo, grandchild);
     root.SetChild(m_childInfo, child);
     return root;
 }
Example #7
0
        private static DomNode Deserialize(BinaryReader reader, Func <string, DomNodeType> getNodeType, List <Reference> references)
        {
            string      typeName = reader.ReadString();
            DomNodeType type     = getNodeType(typeName);

            if (type == null)
            {
                throw new InvalidOperationException("unknown node type");
            }

            DomNode node = new DomNode(type);

            foreach (AttributeInfo info in type.Attributes)
            {
                bool hasAttribute = reader.ReadBoolean();
                if (hasAttribute)
                {
                    // references are reconstituted after all nodes are read
                    if (info.Type.Type == AttributeTypes.Reference)
                    {
                        int refId = reader.ReadInt32();
                        references.Add(new Reference(node, info, refId));
                    }
                    else
                    {
                        string valueString = reader.ReadString();
                        object value       = info.Type.Convert(valueString);
                        node.SetAttribute(info, value);
                    }
                }
            }

            foreach (ChildInfo info in type.Children)
            {
                if (info.IsList)
                {
                    int             count     = reader.ReadInt32();
                    IList <DomNode> childList = node.GetChildList(info);
                    for (int i = 0; i < count; i++)
                    {
                        DomNode child = Deserialize(reader, getNodeType, references);
                        childList.Add(child);
                    }
                }
                else
                {
                    bool hasChild = reader.ReadBoolean();
                    if (hasChild)
                    {
                        DomNode child = Deserialize(reader, getNodeType, references);
                        node.SetChild(info, child);
                    }
                }
            }

            return(node);
        }
Example #8
0
        private DomNode CreatePrototype(IEnumerable <IGameObject> gobs)
        {
            DomNode[] originals = new DomNode[1];

            List <IGameObject> copyList = new List <IGameObject>();
            AABB bound = new AABB();

            foreach (IGameObject gameObject in SelectedGobs)
            {
                IBoundable boundable = gameObject.As <IBoundable>();
                bound.Extend(boundable.BoundingBox);
                Matrix4F world = TransformUtils.ComputeWorldTransform(gameObject);
                originals[0] = gameObject.As <DomNode>();
                DomNode[]   copies = DomNode.Copy(originals);
                IGameObject copy   = copies[0].As <IGameObject>();
                TransformUtils.SetTransform(copy, world);
                copyList.Add(copy);
            }

            DomNode gobchild = null;

            if (copyList.Count > 1)
            {// create group
                IGame            game     = m_contextRegistry.GetActiveContext <IGame>();
                IGameObjectGroup gobgroup = game.CreateGameObjectGroup();
                gobgroup.Translation = bound.Center;
                gobgroup.UpdateTransform();
                Matrix4F worldInv = new Matrix4F();
                worldInv.Invert(gobgroup.Transform);
                foreach (IGameObject gob in copyList)
                {
                    Vec3F translate = gob.Translation;
                    worldInv.Transform(ref translate);
                    gob.Translation = translate;
                    gob.UpdateTransform();
                    gobgroup.GameObjects.Add(gob);
                }
                gobchild = gobgroup.As <DomNode>();
            }
            else
            {
                gobchild = copyList[0].As <DomNode>();
            }

            gobchild.InitializeExtensions();
            gobchild.As <IGameObject>().Translation = new Vec3F(0, 0, 0);

            DomNode prototype = null;

            if (gobchild != null)
            {
                prototype = new DomNode(Schema.prototypeType.Type, Schema.prototypeRootElement);
                prototype.SetChild(Schema.prototypeType.gameObjectChild, gobchild);
            }
            return(prototype);
        }
Example #9
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);
        }
Example #10
0
        private DomNode CreateTree()
        {
            DomNode root       = new DomNode(m_rootType);
            DomNode child      = new DomNode(m_childType);
            DomNode grandchild = new DomNode(m_childType);

            child.SetChild(m_childInfo, grandchild);
            root.SetChild(m_childInfo, child);
            return(root);
        }
Example #11
0
        /// <summary>
        /// Performs initialization when the adapter is connected to the diagram annotation's DomNode,
        /// creating child DomNode for transform and setting its scale.</summary>
        protected override void OnNodeSet()
        {
            DomNode transform = DomNode.GetChild(UISchema.UIControlType.TransformChild);

            if (transform == null)
            {
                transform = new DomNode(UISchema.UITransformType.Type);
                transform.SetAttribute(UISchema.UITransformType.ScaleAttribute, new float[] { 1.0f, 1.0f, 1.0f });
                DomNode.SetChild(UISchema.UIControlType.TransformChild, transform);
            }
        }
Example #12
0
        public void TestRemoveFromParent()
        {
            DomNodeType type      = new DomNodeType("type");
            ChildInfo   childInfo = new ChildInfo("child", type);

            type.Define(childInfo);
            DomNode parent = new DomNode(type);
            DomNode child  = new DomNode(type);

            parent.SetChild(childInfo, child);
            child.RemoveFromParent();
            Assert.Null(parent.GetChild(childInfo));
            Assert.Null(child.Parent);

            // Make sure the removed child has a null Parent. http://tracker.ship.scea.com/jira/browse/WWSATF-1336
            parent.SetChild(childInfo, child);
            DomNode newChild = new DomNode(type);

            parent.SetChild(childInfo, newChild);
            Assert.Null(child.Parent);
            Assert.True(newChild.Parent == parent);
        }
Example #13
0
        public void TestSubscribeAndUnsubscribe()
        {
            DomNode   root      = new DomNode(m_rootType);
            Validator validator = root.As <Validator>();

            DomNode child      = new DomNode(m_childType);
            DomNode grandchild = new DomNode(m_childType);

            child.SetChild(m_childInfo, grandchild);
            root.SetChild(m_childInfo, child);

            ValidationContext context = grandchild.As <ValidationContext>();

            context.RaiseBeginning();
            Assert.True(validator.IsValidating);
            Assert.AreSame(validator.Sender, context);
            Assert.AreSame(validator.E, EventArgs.Empty);
            context.RaiseEnded();

            root.SetChild(m_childInfo, null);
            context.RaiseBeginning();
            Assert.False(validator.IsValidating);
        }
Example #14
0
        void ICommandClient.DoCommand(object commandTag)
        {
            if (!(commandTag is Command))
            {
                return;
            }

            switch ((Command)commandTag)
            {
            case Command.CreateTerrain:
            {
                if (DomNode.GetChild(Schema.xleGameType.terrainChild) == null)
                {
                    var newNode = LevelEditorXLE.Terrain.XLETerrainGob.CreateWithConfigure();
                    if (newNode != null)
                    {
                        DomNode.SetChild(Schema.xleGameType.terrainChild, newNode);
                    }
                }
                break;
            }

            case Command.CreatePlacementsFolder:
            {
                if (DomNode.GetChild(Schema.xleGameType.placementsChild) == null)
                {
                    var newNode = PlacementsFolder.CreateWithConfigure();
                    if (newNode != null)
                    {
                        DomNode.SetChild(Schema.xleGameType.placementsChild, newNode);
                    }
                }
                break;
            }

            case Command.CreateEnvironmentSetting:
            {
                var envFolder = EnvSettingsFolder;
                envFolder.AddChild(
                    XLEEnvSettings.Create(envFolder.GetNameForNewChild()));
                break;
            }

            case Command.CreateTriMeshMarker:
            {
                this.As <IGame>().RootGameObjectFolder.As <IHierarchical>().AddChild(Markers.TriMeshMarker.Create());
                break;
            }
            }
        }
        private DomNode GetOrCreateMissingTemplateNode(string guid)
        {
            if (m_missingTemplates == null)
                m_missingTemplates = new Dictionary<string, DomNode>();
            DomNode templateNode;
            if (m_missingTemplates.TryGetValue(guid, out templateNode))
                return templateNode;

            templateNode = new DomNode(Schema.missingTemplateType.Type);
            templateNode.SetAttribute(Schema.missingTemplateType.guidAttribute, guid);
            var moduleChild = new DomNode(Schema.missingModuleType.Type);
            templateNode.SetChild(Schema.missingTemplateType.moduleChild, moduleChild);
            return templateNode;
        }
Example #16
0
        public void TestGetChild()
        {
            DomNodeType type      = new DomNodeType("type");
            ChildInfo   childInfo = new ChildInfo("child", type);

            type.Define(childInfo);

            DomNode parent = new DomNode(type);
            DomNode child  = new DomNode(type);

            parent.SetChild(childInfo, child);
            Assert.AreSame(parent.GetChild(childInfo), child);
            Assert.Throws <InvalidOperationException>(delegate { parent.GetChildList(childInfo); });
        }
Example #17
0
        public void TestGetRoots()
        {
            DomNodeType type      = new DomNodeType("type");
            ChildInfo   childInfo = new ChildInfo("child", type);

            type.Define(childInfo);

            DomNode child       = new DomNode(type);
            DomNode parent      = new DomNode(type);
            DomNode grandparent = new DomNode(type);

            parent.SetChild(childInfo, child);
            grandparent.SetChild(childInfo, parent);
            DomNode child2 = new DomNode(type);

            Utilities.TestSequenceEqual(DomNode.GetRoots(new DomNode[] { grandparent, child, child2 }), grandparent, child2);
        }
Example #18
0
        public void TestParentChildren()
        {
            DomNodeType type       = new DomNodeType("type");
            ChildInfo   childInfo1 = new ChildInfo("child1", type);

            type.Define(childInfo1);
            ChildInfo childInfo2 = new ChildInfo("child2", type, true);

            type.Define(childInfo2);

            DomNode child1 = new DomNode(type);
            DomNode child2 = new DomNode(type);
            DomNode parent = new DomNode(type);

            parent.SetChild(childInfo1, child1);
            parent.GetChildList(childInfo2).Add(child2);
            Utilities.TestSequenceEqual(parent.Children, child1, child2);
        }
Example #19
0
            /// <summary>
            /// Run the copier
            /// </summary>
            /// <param name="domProjectTree">Tree to copy</param>
            /// <param name="domTempTree">Copied tree</param>
            public override void Run(DomNode domProjectTree, DomNode domTempTree)
            {
                var lstToCopy = new List <DomNode>();

                GatherNodeTypes(domTempTree, m_nodeType, lstToCopy);

                foreach (var domNode in lstToCopy)
                {
                    var info = domNode.ChildInfo;
                    if (info.IsList)
                    {
                        domProjectTree.GetChildList(info).Add(domNode);
                    }
                    else
                    {
                        domProjectTree.SetChild(info, domNode);
                    }
                }
            }
Example #20
0
        /// <summary>
        /// When overridden in a derived class, sets the value of the component to a different value</summary>
        /// <param name="component">The component with the property value that is to be set</param>
        /// <param name="value">The new value</param>
        public override void SetValue(object component, object value)
        {
            DomNode node = GetNode(component);

            if (node != null)
            {
                if (m_childInfo.IsList)
                {
                    IList <DomNode> targetList = node.GetChildList(m_childInfo);
                    IList <DomNode> valueList  = value as IList <DomNode>;
                    if (targetList != null && valueList != null)
                    {
                        // Diff targetList and valueList
                        int i = 0;
                        while (i < Math.Min(valueList.Count, targetList.Count) && targetList[i] == valueList[i])
                        {
                            ++i;
                        }
                        // => Now they are identical up to index i

                        // Remove excess items from target list
                        while (targetList.Count > i)
                        {
                            targetList.RemoveAt(i);
                        }

                        // Add additional items from value list
                        for (; i < valueList.Count; i++)
                        {
                            targetList.Add(valueList[i]);
                        }
                    }
                }
                else
                {
                    DomNode valueNode = GetNode(value);
                    if (valueNode != null)
                    {
                        node.SetChild(m_childInfo, valueNode);
                    }
                }
            }
        }
Example #21
0
        public void TestReparentInTransaction()
        {
            DomNode a = m_root.GetChild(ChildInfo);
            DomNode b = a.GetChild(ChildInfo);

            b.RemoveFromParent();

            // root -- a  ==>
            // root -- b -- a
            m_events.Clear();
            m_transactionContext.DoTransaction(() =>
            {
                a.SetAttribute(StringAttrInfo, "foo1");
                a.RemoveFromParent();
                m_root.SetChild(ChildInfo, b);
                b.SetChild(ChildInfo, a);
                b.SetAttribute(StringAttrInfo, "foo1");
            }, "test transaction 1");

            Assert.IsTrue(m_events.Count == 2);
            CheckChildRemovedEvent(m_events[0], m_root, a);
            CheckChildInsertedEvent(m_events[1], m_root, b);
        }
Example #22
0
        public void TestGetRoots()
        {
            DomNodeType type = new DomNodeType("type");
            ChildInfo childInfo = new ChildInfo("child", type);
            type.Define(childInfo);

            DomNode child = new DomNode(type);
            DomNode parent = new DomNode(type);
            DomNode grandparent = new DomNode(type);
            parent.SetChild(childInfo, child);
            grandparent.SetChild(childInfo, parent);
            DomNode child2 = new DomNode(type);
            Utilities.TestSequenceEqual(DomNode.GetRoots(new DomNode[] { grandparent, child, child2 }), grandparent, child2);
        }
Example #23
0
        public void TestParentChildren()
        {
            DomNodeType type = new DomNodeType("type");
            ChildInfo childInfo1 = new ChildInfo("child1", type);
            type.Define(childInfo1);
            ChildInfo childInfo2 = new ChildInfo("child2", type, true);
            type.Define(childInfo2);

            DomNode child1 = new DomNode(type);
            DomNode child2 = new DomNode(type);
            DomNode parent = new DomNode(type);
            parent.SetChild(childInfo1, child1);
            parent.GetChildList(childInfo2).Add(child2);
            Utilities.TestSequenceEqual(parent.Children, child1, child2);
        }
Example #24
0
        private static DomNode Deserialize(BinaryReader reader, Func<string, DomNodeType> getNodeType, List<Reference> references)
        {
            string typeName = reader.ReadString();
            DomNodeType type = getNodeType(typeName);
            if (type == null)
                throw new InvalidOperationException("unknown node type");

            DomNode node = new DomNode(type);

            foreach (AttributeInfo info in type.Attributes)
            {
                bool hasAttribute = reader.ReadBoolean();
                if (hasAttribute)
                {
                    // references are reconstituted after all nodes are read
                    if (info.Type.Type == AttributeTypes.Reference)
                    {
                        int refId = reader.ReadInt32();
                        references.Add(new Reference(node, info, refId));
                    }
                    else
                    {
                        string valueString = reader.ReadString();
                        object value = info.Type.Convert(valueString);
                        node.SetAttribute(info, value);
                    }
                }
            }

            foreach (ChildInfo info in type.Children)
            {
                if (info.IsList)
                {
                    int count = reader.ReadInt32();
                    IList<DomNode> childList = node.GetChildList(info);
                    for (int i = 0; i < count; i++)
                    {
                        DomNode child = Deserialize(reader, getNodeType, references);
                        childList.Add(child);
                    }
                }
                else
                {
                    bool hasChild = reader.ReadBoolean();
                    if (hasChild)
                    {
                        DomNode child = Deserialize(reader, getNodeType, references);
                        node.SetChild(info, child);
                    }
                }
            }

            return node;
        }
Example #25
0
        // Create circuit DOM hierarchy programmatically
        static public DomNode CreateTestCircuitProgrammatically(SchemaLoader schemaLoader)
        {
            var rootNode = new DomNode(Schema.circuitDocumentType.Type, Schema.circuitRootElement);        
            // create an empty root prototype folder( required child by schema)
            rootNode.SetChild(
                Schema.circuitDocumentType.prototypeFolderChild,
                new DomNode(Schema.prototypeFolderType.Type));
            
            var circuit = rootNode.Cast<Circuit>();

            var inputFiles = new DomNode(Schema.groupType.Type).Cast<Group>();
            inputFiles.Id = "groupInputFiles";
            inputFiles.Name = "Input Files".Localize();
            inputFiles.Bounds = new Rectangle(64, 96, 0, 0); // set node location, size will be auto-computed
 
            var firstWavgGroup = new DomNode(Schema.groupType.Type).Cast<Group>();
            firstWavgGroup.Id = "first.Wav";
            firstWavgGroup.Name = "first".Localize("as in, 'the first file'") + ".wav";

            var buttonType = schemaLoader.GetNodeType(Schema.NS + ButtonTypeName);
            var button1 = new DomNode(buttonType).Cast<Module>();
            button1.Id = "button1";
            button1.Bounds = new Rectangle(0, 0, 0, 0);

            var button2 = new DomNode(buttonType).Cast<Module>();
            button2.Bounds = new Rectangle(0, 64, 0, 0);
            button2.Id = "button2";

            firstWavgGroup.Elements.Add(button1);
            firstWavgGroup.Elements.Add(button2);
            firstWavgGroup.Expanded = true;
            firstWavgGroup.Update();


            var secondWavgGroup = new DomNode(Schema.groupType.Type).Cast<Group>();
            secondWavgGroup.Id = "second.Wav";
            secondWavgGroup.Name = "second".Localize("as in, 'the second file'") + ".wav";

            var button3 = new DomNode(buttonType).Cast<Module>();
            button3.Id = "button3";
            button3.Bounds = new Rectangle(0, 0, 0, 0);

            var button4 = new DomNode(buttonType).Cast<Module>();
            button4.Bounds = new Rectangle(0, 64, 0, 0);
            button4.Id = "button4";

            secondWavgGroup.Elements.Add(button3);
            secondWavgGroup.Elements.Add(button4);
            secondWavgGroup.Expanded = true;
            secondWavgGroup.Update();
            secondWavgGroup.Bounds = new Rectangle(0, 224, 0, 0);
  
            inputFiles.Elements.Add(firstWavgGroup);
            inputFiles.Elements.Add(secondWavgGroup);
            inputFiles.Update();
            inputFiles.Expanded = true;

            circuit.Elements.Add(inputFiles);


            var structure = new DomNode(Schema.groupType.Type).Cast<Group>();
            structure.Id = "structure".Localize("this is the name of a group of circuit elements; the name is arbitrary");
            structure.Name = "structure".Localize("this is the name of a group of circuit elements; the name is arbitrary");
            structure.Bounds = new Rectangle(352, 96, 0, 0); 
 

            var subStream0 = new DomNode(Schema.groupType.Type).Cast<Group>();
            subStream0.Id = "subStream0".Localize("this is the name of a group of circuit elements; the name is arbitrary");
            subStream0.Name = "sub-stream 0".Localize("this is the name of a group of circuit elements; the name is arbitrary");

            var lightType = schemaLoader.GetNodeType(Schema.NS + LightTypeName);

            var light1 = new DomNode(lightType).Cast<Module>();
            light1.Id = "light1";
            light1.Bounds = new Rectangle(0, 0, 0, 0);

            var light2 = new DomNode(lightType).Cast<Module>();
            light2.Id = "light2";
            light2.Bounds = new Rectangle(0, 64, 0, 0);

            var light3 = new DomNode(lightType).Cast<Module>();
            light3.Id = "light3";
            light3.Bounds = new Rectangle(0, 128, 0, 0);

            var light4 = new DomNode(lightType).Cast<Module>();
            light4.Id = "light4";
            light4.Bounds = new Rectangle(0, 192, 0, 0);

            var light5 = new DomNode(lightType).Cast<Module>();
            light5.Id = "light5";
            light5.Bounds = new Rectangle(0, 256, 0, 0);

            var light6 = new DomNode(lightType).Cast<Module>();
            light6.Id = "light6";
            light6.Bounds = new Rectangle(0, 320, 0, 0);


            subStream0.Elements.Add(light1);
            subStream0.Elements.Add(light2);
            subStream0.Elements.Add(light3);
            subStream0.Elements.Add(light4);
            subStream0.Elements.Add(light5);
            subStream0.Elements.Add(light6);
            subStream0.Expanded = true;
            subStream0.Update(); // this will generate group pins needed for edge connection


            structure.Elements.Add(subStream0);
            structure.Expanded = true;
            structure.Update();

            circuit.Elements.Add(structure);

            // Note on 11/12/2013: adding wires currently crashes. Nested circuit groups aren't officially supported anyways.
            // make some edges betwen InputFiles & structure
            //var connection0 = CircuitAddEdge(inputFiles, 0, structure, 0);
            //circuit.Wires.Add(connection0);
            //var connection1 = CircuitAddEdge(inputFiles, 1, structure, 1);
            //circuit.Wires.Add(connection1);
            //var connection2 = CircuitAddEdge(inputFiles, 2, structure, 3);
            //circuit.Wires.Add(connection2);
            //var connection3 = CircuitAddEdge(inputFiles, 3, structure, 5);
            //circuit.Wires.Add(connection3);

            return rootNode;
        }
Example #26
0
        protected override void OnNodeSet()
        {
            base.OnNodeSet();

            if (string.IsNullOrEmpty(GetAttribute <string>(moduleType.labelAttribute)))
            {
                SetAttribute(moduleType.labelAttribute, GetAttribute <string>(moduleType.nameAttribute));
            }

            // Pull image icon image from node definition
            var nodeDef = DomNode.Type.GetTag <SF.Tong.Schema.NodeTypeInfo>();

            m_Image = string.IsNullOrEmpty(nodeDef.Icon) ? null : ResourceUtil.GetImage32(nodeDef.Icon);

            // Create non-string child classes
            if (DomNode.Children != null)
            {
                foreach (var childInfo in DomNode.Type.Children)
                {
                    if (childInfo.IsList)
                    {
                        continue;
                    }
                    if (DomNode.GetChild(childInfo) != null)
                    {
                        continue;
                    }

                    var newChild = new DomNode(childInfo.Type);
                    DomNode.SetChild(childInfo, newChild);
                }
            }

            // Add sockets for attributes
            if (DomNode.Type.Attributes != null)
            {
                foreach (var attrInfo in DomNode.Type.Attributes)
                {
                    var attrRule = attrInfo.GetRule <GameDataAttributeRule>();
                    if (attrRule == null || attrRule.SchemaProperty == null)
                    {
                        continue;
                    }

                    switch (attrRule.SchemaProperty.Socket)
                    {
                    case SF.Tong.Schema.SocketType.Input:
                        m_Inputs.Add(new ElementType.Pin(attrInfo.Name, attrInfo.Type, m_Inputs.Count, allowFanIn: attrRule.SchemaProperty.AllowMultipleInput));
                        break;

                    case SF.Tong.Schema.SocketType.Output:
                        m_Outputs.Add(new ElementType.Pin(attrInfo.Name, attrInfo.Type, m_Outputs.Count, allowFanOut: attrRule.SchemaProperty.AllowMultipleOutput));
                        break;

                    case SF.Tong.Schema.SocketType.InOut:
                        m_Inputs.Add(new ElementType.Pin(attrInfo.Name, attrInfo.Type, m_Inputs.Count, allowFanIn: attrRule.SchemaProperty.AllowMultipleInput));
                        m_Outputs.Add(new ElementType.Pin(attrInfo.Name, attrInfo.Type, m_Outputs.Count, allowFanOut: attrRule.SchemaProperty.AllowMultipleOutput));
                        break;

                    default:
                        break;
                    }
                }
            }


            // Create child sockets
            if (DomNode.Children != null)
            {
                foreach (var child in DomNode.Children)
                {
                    if (child.ChildInfo.Type != socketType.Type)
                    {
                        continue;
                    }

                    string socketName = GetBaseNameFor(child.ChildInfo, child);

                    // Only output can vary
                    var newPin = new ElementType.Pin(socketName, AttributeType.BooleanType, m_Outputs.Count);
                    m_Outputs.Add(newPin);
                }
            }


            // Update socket as new a child node is added
            DomNode.ChildInserted += (sender, args) =>
            {
                if (DomNode != args.Parent)
                {
                    return;
                }

                if (args.ChildInfo.Type == socketType.Type)
                {
                    string socketName = GetBaseNameFor(args.ChildInfo, args.Child);

                    // Only output can vary
                    var newPin = new ElementType.Pin(socketName, AttributeType.BooleanType, m_Outputs.Count);
                    m_Outputs.Add(newPin);
                }
            };

            // Update socket as new a child node is removed
            DomNode.ChildRemoved += (sender, args) =>
            {
                if (DomNode != args.Parent)
                {
                    return;
                }

                if (args.ChildInfo.Type == socketType.Type)
                {
                    string socketName = GetBaseNameFor(args.ChildInfo, args.Child);

                    // Only output can vary
                    int iSocket = 0;
                    for (; iSocket < m_Outputs.Count; iSocket++)
                    {
                        var output = m_Outputs[iSocket];
                        if (output.Name == socketName)
                        {
                            m_Outputs.RemoveAt(iSocket);
                            break;
                        }
                    }

                    // fix up index
                    for (; iSocket < m_Outputs.Count; iSocket++)
                    {
                        var output = m_Outputs[iSocket];
                        output.Index = iSocket;
                    }
                }
            };

            // For title text
            UpdateTitleText();

            DomNode.AttributeChanged += OnAttributeChanged;
        }
Example #27
0
        public void TestSubscribeAndUnsubscribe()
        {
            DomNode root = new DomNode(RootType);
            Validator validator = root.As<Validator>();

            DomNode child = new DomNode(ChildType);
            DomNode grandchild = new DomNode(ChildType);
            child.SetChild(ChildInfo, grandchild);
            root.SetChild(ChildInfo, child);

            ValidationContext context = grandchild.As<ValidationContext>();
            context.RaiseBeginning();
            Assert.True(validator.IsValidating);
            Assert.AreSame(validator.Sender, context);
            Assert.AreSame(validator.E, EventArgs.Empty);
            context.RaiseEnded();

            root.SetChild(ChildInfo, null);
            context.RaiseBeginning();
            Assert.False(validator.IsValidating);
        }
Example #28
0
        private DomNode GetOrCreateMissingTemplateNode(string guid)
        {
            if (m_missingTemplates == null)
                m_missingTemplates = new Dictionary<string, DomNode>();
            DomNode templateNode;
            if (m_missingTemplates.TryGetValue(guid, out templateNode))
                return templateNode;

            templateNode = new DomNode(Schema.missingTemplateType.Type);
            templateNode.SetAttribute(Schema.missingTemplateType.guidAttribute, guid);
            var moduleChild = new DomNode(Schema.missingModuleType.Type);
            templateNode.SetChild(Schema.missingTemplateType.moduleChild, moduleChild);
            return templateNode;
        }
Example #29
0
        public void TestChildRemoveEvents()
        {
            DomNodeType type = new DomNodeType("type");
            ChildInfo info = new ChildInfo("child", type);
            ChildInfo infoList = new ChildInfo("childList", type, true);
            type.Define(info);
            type.Define(infoList);
            DomNode test = new DomNode(type);
            test.ChildRemoving += new EventHandler<ChildEventArgs>(test_ChildRemoving);
            test.ChildRemoved += new EventHandler<ChildEventArgs>(test_ChildRemoved);

            // test child
            DomNode child = new DomNode(type);
            test.SetChild(info, child);
            ChildRemovingArgs = null;
            ChildRemovedArgs = null;
            test.SetChild(info, null);
            ChildEventArgs expected = new ChildEventArgs(test, info, child, 0);
            Assert.True(Equals(ChildRemovingArgs, expected));
            Assert.True(Equals(ChildRemovedArgs, expected));

            // test inserting a child when there is one there already
            test.SetChild(info, child);
            DomNode newChild = new DomNode(type);
            ChildRemovingArgs = null;
            ChildRemovedArgs = null;
            test.SetChild(info, newChild);
            expected = new ChildEventArgs(test, info, child, 0);
            Assert.True(Equals(ChildRemovingArgs, expected));
            Assert.True(Equals(ChildRemovedArgs, expected));

            // test child list
            IList<DomNode> list = test.GetChildList(infoList);
            DomNode child2 = new DomNode(type);
            list.Add(child2);
            DomNode child3 = new DomNode(type);
            list.Add(child3);
            ChildRemovingArgs = null;
            ChildRemovedArgs = null;
            list.Remove(child3);
            expected = new ChildEventArgs(test, infoList, child3, 1);
            Assert.True(Equals(ChildRemovingArgs, expected));
            Assert.True(Equals(ChildRemovedArgs, expected));
            ChildRemovingArgs = null;
            ChildRemovedArgs = null;
            list.Remove(child2);
            expected = new ChildEventArgs(test, infoList, child2, 0);
            Assert.True(Equals(ChildRemovingArgs, expected));
            Assert.True(Equals(ChildRemovedArgs, expected));
        }
Example #30
0
        /// <summary>
        /// Reads the node specified by the child metadata</summary>
        /// <param name="nodeInfo">Child metadata for node</param>
        /// <param name="reader">XML reader</param>
        /// <returns>DomNode specified by the child metadata</returns>
        protected virtual DomNode ReadElement(ChildInfo nodeInfo, XmlReader reader)
        {
            // handle polymorphism, if necessary
            DomNodeType type = GetChildType(nodeInfo.Type, reader);
            int index = type.Name.LastIndexOf(':');
            string typeNS = type.Name.Substring(0, index);

            DomNode node = new DomNode(type, nodeInfo);

            // read attributes
            while (reader.MoveToNextAttribute())
            {
                if (reader.Prefix == string.Empty ||
                    reader.LookupNamespace(reader.Prefix) == typeNS)
                {
                    AttributeInfo attributeInfo = type.GetAttributeInfo(reader.LocalName);
                    if (attributeInfo != null)
                    {
                        string valueString = reader.Value;
                        if (attributeInfo.Type.Type == AttributeTypes.Reference)
                        {
                            // save reference so it can be resolved after all nodes have been read
                            m_nodeReferences.Add(new XmlNodeReference(node, attributeInfo, valueString));
                        }
                        else
                        {
                            object value = attributeInfo.Type.Convert(valueString);
                            node.SetAttribute(attributeInfo, value);
                        }
                    }
                }
            }

            // add node to map if it has an id
            if (node.Type.IdAttribute != null)
            {
                string id = node.GetId();
                if (!string.IsNullOrEmpty(id))
                    m_nodeDictionary[id] = node; // don't Add, in case there are multiple DomNodes with the same id
            }

            reader.MoveToElement();

            if (!reader.IsEmptyElement)
            {
                // read child elements
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        // look up metadata for this element
                        ChildInfo childInfo = type.GetChildInfo(reader.LocalName);
                        if (childInfo != null)
                        {
                            DomNode childObject = ReadElement(childInfo, reader);
                            // at this point, child is a fully populated sub-tree

                            if (childInfo.IsList)
                            {
                                node.GetChildList(childInfo).Add(childObject);
                            }
                            else
                            {
                                node.SetChild(childInfo, childObject);
                            }
                        }
                        else
                        {
                            // try reading as an attribute
                            AttributeInfo attributeInfo = type.GetAttributeInfo(reader.LocalName);
                            if (attributeInfo != null)
                            {
                                reader.MoveToElement();

                                if (!reader.IsEmptyElement)
                                {
                                    // read element text
                                    while (reader.Read())
                                    {
                                        if (reader.NodeType == XmlNodeType.Text)
                                        {
                                            object value = attributeInfo.Type.Convert(reader.Value);
                                            node.SetAttribute(attributeInfo, value);
                                            // skip child elements, as this is an attribute value
                                            reader.Skip();
                                            break;
                                        }
                                        if (reader.NodeType == XmlNodeType.EndElement)
                                        {
                                            break;
                                        }
                                    }

                                    reader.MoveToContent();
                                }
                            }
                            else
                            {
                                // skip unrecognized element
                                reader.Skip();
                                // if that takes us to the end of the enclosing element, break
                                if (reader.NodeType == XmlNodeType.EndElement)
                                    break;
                            }
                        }
                    }
                    else if (reader.NodeType == XmlNodeType.Text)
                    {
                        AttributeInfo attributeInfo = type.GetAttributeInfo(string.Empty);
                        if (attributeInfo != null)
                        {
                            object value = attributeInfo.Type.Convert(reader.Value);
                            node.SetAttribute(attributeInfo, value);
                        }
                    }
                    else if (reader.NodeType == XmlNodeType.EndElement)
                    {
                        break;
                    }
                }
            }

            reader.MoveToContent();

            return node;
        }
Example #31
0
File: ObjFile.cs Project: zparr/ATF
        /// <summary>
        /// Populates DomNode with data from stream data</summary>
        /// <param name="stream">Stream to read data into</param>
        /// <param name="node">Node to populate</param>
        /// <param name="resolvedUri">URI representing object file</param>
        public static void PopulateDomNode(Stream stream, ref DomNode node, Uri resolvedUri)
        {
            // Parse .obj file
            var obj = new ObjFile();

            obj.Read(stream, resolvedUri);

            if (node == null)
            {
                node = new DomNode(Schema.nodeType.Type);
            }

            // Populate mesh
            var mesh = new DomNode(Schema.meshType.Type);

            mesh.SetAttribute(Schema.meshType.nameAttribute, Path.GetFileName(resolvedUri.LocalPath));

            var vertexArray = new DomNode(Schema.meshType_vertexArray.Type);

            // Populate primitive data
            foreach (Group group in obj.m_groups.Values)
            {
                foreach (FaceSet face in group.FaceSets.Values)
                {
                    var primitive = new DomNode(Schema.vertexArray_primitives.Type);
                    primitive.SetAttribute(Schema.vertexArray_primitives.indicesAttribute, face.Indices.ToArray());
                    primitive.SetAttribute(Schema.vertexArray_primitives.sizesAttribute, face.Sizes.ToArray());
                    primitive.SetAttribute(Schema.vertexArray_primitives.typeAttribute, "POLYGONS");

                    // Populate shader
                    MaterialDef material;
                    obj.m_mtl.Materials.TryGetValue(face.MaterialName, out material);

                    if (material != null)
                    {
                        string texture = null;
                        if (material.TextureName != null)
                        {
                            texture = new Uri(resolvedUri, material.TextureName).AbsolutePath;
                        }

                        var shader = new DomNode(Schema.shaderType.Type);
                        shader.SetAttribute(Schema.shaderType.nameAttribute, material.Name);
                        shader.SetAttribute(Schema.shaderType.ambientAttribute, material.Ambient);
                        shader.SetAttribute(Schema.shaderType.diffuseAttribute, material.Diffuse);
                        shader.SetAttribute(Schema.shaderType.shininessAttribute, material.Shininess);
                        shader.SetAttribute(Schema.shaderType.specularAttribute, material.Specular);
                        shader.SetAttribute(Schema.shaderType.textureAttribute, texture);

                        primitive.SetChild(Schema.vertexArray_primitives.shaderChild, shader);
                    }

                    // Note: Bindings must be in the order: normal, map1, position
                    DomNode binding;
                    if (face.HasNormals)
                    {
                        binding = new DomNode(Schema.primitives_binding.Type);
                        binding.SetAttribute(Schema.primitives_binding.sourceAttribute, "normal");
                        primitive.GetChildList(Schema.vertexArray_primitives.bindingChild).Add(binding);
                    }

                    if (face.HasTexCoords)
                    {
                        binding = new DomNode(Schema.primitives_binding.Type);
                        binding.SetAttribute(Schema.primitives_binding.sourceAttribute, "map1");
                        primitive.GetChildList(Schema.vertexArray_primitives.bindingChild).Add(binding);
                    }

                    binding = new DomNode(Schema.primitives_binding.Type);
                    binding.SetAttribute(Schema.primitives_binding.sourceAttribute, "position");
                    primitive.GetChildList(Schema.vertexArray_primitives.bindingChild).Add(binding);

                    vertexArray.GetChildList(Schema.meshType_vertexArray.primitivesChild).Add(primitive);
                }
            }

            // Populate array data
            DomNode array;

            if (obj.m_normals.Count > 0)
            {
                array = new DomNode(Schema.vertexArray_array.Type);
                array.SetAttribute(Schema.vertexArray_array.Attribute, obj.m_normals.ToArray());
                array.SetAttribute(Schema.vertexArray_array.countAttribute, obj.m_normals.Count / 3);
                array.SetAttribute(Schema.vertexArray_array.nameAttribute, "normal");
                array.SetAttribute(Schema.vertexArray_array.strideAttribute, 3);

                vertexArray.GetChildList(Schema.meshType_vertexArray.arrayChild).Add(array);
            }

            if (obj.m_texcoords.Count > 0)
            {
                array = new DomNode(Schema.vertexArray_array.Type);
                array.SetAttribute(Schema.vertexArray_array.Attribute, obj.m_texcoords.ToArray());
                array.SetAttribute(Schema.vertexArray_array.countAttribute, obj.m_texcoords.Count / 2);
                array.SetAttribute(Schema.vertexArray_array.nameAttribute, "map1");
                array.SetAttribute(Schema.vertexArray_array.strideAttribute, 2);

                vertexArray.GetChildList(Schema.meshType_vertexArray.arrayChild).Add(array);
            }

            array = new DomNode(Schema.vertexArray_array.Type);
            array.SetAttribute(Schema.vertexArray_array.Attribute, obj.m_positions.ToArray());
            array.SetAttribute(Schema.vertexArray_array.countAttribute, obj.m_positions.Count / 3);
            array.SetAttribute(Schema.vertexArray_array.nameAttribute, "position");
            array.SetAttribute(Schema.vertexArray_array.strideAttribute, 3);

            vertexArray.GetChildList(Schema.meshType_vertexArray.arrayChild).Add(array);

            // Set mesh elements
            mesh.SetChild(Schema.meshType.vertexArrayChild, vertexArray);
            node.SetChild(Schema.nodeType.meshChild, mesh);
        }
        /// <summary>
        /// Create circuit DOM hierarchy programmatically</summary>
        /// <param name="schemaLoader">Schema loader</param>
        /// <returns>Tree root DomNode</returns>
        static public DomNode CreateTestCircuitProgrammatically(SchemaLoader schemaLoader)
        {
            var rootNode = new DomNode(Schema.circuitDocumentType.Type, Schema.circuitRootElement);

            // create an empty root prototype folder( required child by schema)
            rootNode.SetChild(
                Schema.circuitDocumentType.prototypeFolderChild,
                new DomNode(Schema.prototypeFolderType.Type));

            var circuit = rootNode.Cast <Circuit>();

            var inputFiles = new DomNode(Schema.groupType.Type).Cast <Group>();

            inputFiles.Id     = "groupInputFiles";
            inputFiles.Name   = "Input Files".Localize();
            inputFiles.Bounds = new Rectangle(64, 96, 0, 0); // set node location, size will be auto-computed

            var firstWavgGroup = new DomNode(Schema.groupType.Type).Cast <Group>();

            firstWavgGroup.Id   = "first.Wav";
            firstWavgGroup.Name = "first".Localize("as in, 'the first file'") + ".wav";

            var buttonType = schemaLoader.GetNodeType(Schema.NS + ButtonTypeName);
            var button1    = new DomNode(buttonType).Cast <Module>();

            button1.Id     = "button1";
            button1.Bounds = new Rectangle(0, 0, 0, 0);

            var button2 = new DomNode(buttonType).Cast <Module>();

            button2.Bounds = new Rectangle(0, 64, 0, 0);
            button2.Id     = "button2";

            firstWavgGroup.Elements.Add(button1);
            firstWavgGroup.Elements.Add(button2);
            firstWavgGroup.Expanded = true;
            firstWavgGroup.Update();


            var secondWavgGroup = new DomNode(Schema.groupType.Type).Cast <Group>();

            secondWavgGroup.Id   = "second.Wav";
            secondWavgGroup.Name = "second".Localize("as in, 'the second file'") + ".wav";

            var button3 = new DomNode(buttonType).Cast <Module>();

            button3.Id     = "button3";
            button3.Bounds = new Rectangle(0, 0, 0, 0);

            var button4 = new DomNode(buttonType).Cast <Module>();

            button4.Bounds = new Rectangle(0, 64, 0, 0);
            button4.Id     = "button4";

            secondWavgGroup.Elements.Add(button3);
            secondWavgGroup.Elements.Add(button4);
            secondWavgGroup.Expanded = true;
            secondWavgGroup.Update();
            secondWavgGroup.Bounds = new Rectangle(0, 224, 0, 0);

            inputFiles.Elements.Add(firstWavgGroup);
            inputFiles.Elements.Add(secondWavgGroup);
            inputFiles.Update();
            inputFiles.Expanded = true;

            circuit.Elements.Add(inputFiles);


            var structure = new DomNode(Schema.groupType.Type).Cast <Group>();

            structure.Id     = "structure".Localize("this is the name of a group of circuit elements; the name is arbitrary");
            structure.Name   = "structure".Localize("this is the name of a group of circuit elements; the name is arbitrary");
            structure.Bounds = new Rectangle(352, 96, 0, 0);


            var subStream0 = new DomNode(Schema.groupType.Type).Cast <Group>();

            subStream0.Id   = "subStream0".Localize("this is the name of a group of circuit elements; the name is arbitrary");
            subStream0.Name = "sub-stream 0".Localize("this is the name of a group of circuit elements; the name is arbitrary");

            var lightType = schemaLoader.GetNodeType(Schema.NS + LightTypeName);

            var light1 = new DomNode(lightType).Cast <Module>();

            light1.Id     = "light1";
            light1.Bounds = new Rectangle(0, 0, 0, 0);

            var light2 = new DomNode(lightType).Cast <Module>();

            light2.Id     = "light2";
            light2.Bounds = new Rectangle(0, 64, 0, 0);

            var light3 = new DomNode(lightType).Cast <Module>();

            light3.Id     = "light3";
            light3.Bounds = new Rectangle(0, 128, 0, 0);

            var light4 = new DomNode(lightType).Cast <Module>();

            light4.Id     = "light4";
            light4.Bounds = new Rectangle(0, 192, 0, 0);

            var light5 = new DomNode(lightType).Cast <Module>();

            light5.Id     = "light5";
            light5.Bounds = new Rectangle(0, 256, 0, 0);

            var light6 = new DomNode(lightType).Cast <Module>();

            light6.Id     = "light6";
            light6.Bounds = new Rectangle(0, 320, 0, 0);


            subStream0.Elements.Add(light1);
            subStream0.Elements.Add(light2);
            subStream0.Elements.Add(light3);
            subStream0.Elements.Add(light4);
            subStream0.Elements.Add(light5);
            subStream0.Elements.Add(light6);
            subStream0.Expanded = true;
            subStream0.Update(); // this will generate group pins needed for edge connection


            structure.Elements.Add(subStream0);
            structure.Expanded = true;
            structure.Update();

            circuit.Elements.Add(structure);

            // first make all group pins are visible so we can connect them
            foreach (var groupPin in inputFiles.InputGroupPins)
            {
                groupPin.Visible = true;
            }
            foreach (var groupPin in inputFiles.OutputGroupPins)
            {
                groupPin.Visible = true;
            }
            foreach (var groupPin in structure.InputGroupPins)
            {
                groupPin.Visible = true;
            }
            foreach (var groupPin in structure.OutputGroupPins)
            {
                groupPin.Visible = true;
            }

            // make some edges between InputFiles & structure
            var connection0 = CircuitAddEdge(inputFiles, 0, structure, 0);

            circuit.Wires.Add(connection0);
            var connection1 = CircuitAddEdge(inputFiles, 1, structure, 1);

            circuit.Wires.Add(connection1);
            var connection2 = CircuitAddEdge(inputFiles, 2, structure, 3);

            circuit.Wires.Add(connection2);
            var connection3 = CircuitAddEdge(inputFiles, 3, structure, 5);

            circuit.Wires.Add(connection3);

            return(rootNode);
        }
Example #33
0
        /// <summary>
        /// Opens or creates a document at the given URI.
        /// It creates a D2dAdaptableControl with control adapters for the document.
        /// It registers this control with the hosting service so that the control appears
        /// in the Windows docking framework.</summary>
        /// <param name="uri">Document URI</param>
        /// <returns>Document, or null if the document couldn't be opened or created</returns>
        public IDocument Open(Uri uri)
        {
            DomNode node     = null;
            string  filePath = uri.LocalPath;

            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(m_schemaLoader);
                    node = reader.Read(stream, uri);
                }
            }
            else
            {
                // create new document by creating a Dom node of the root type defined by the schema
                node = new DomNode(Schema.statechartDocumentType.Type, Schema.statechartRootElement);
                // create an empty root prototype folder
                node.SetChild(
                    Schema.statechartDocumentType.prototypeFolderChild,
                    new DomNode(Schema.prototypeFolderType.Type));
            }

            Document statechartDocument = null;

            if (node != null)
            {
                // AdaptableControl was registered as an extension by the schema loader
                var control = new D2dAdaptableControl();
                control.SuspendLayout();

                control.BackColor = SystemColors.ControlLight;
                control.AllowDrop = true;

                var transformAdapter = new TransformAdapter();
                transformAdapter.UniformScale = true;
                transformAdapter.MinScale     = new PointF(0.25f, 0.25f);
                transformAdapter.MaxScale     = new PointF(4, 4);
                var viewingAdapter = new ViewingAdapter(transformAdapter);
                var canvasAdapter  = new CanvasAdapter(new Rectangle(0, 0, 1000, 1000));

                var autoTranslateAdapter      = new AutoTranslateAdapter(transformAdapter);
                var mouseTransformManipulator = new MouseTransformManipulator(transformAdapter);
                var mouseWheelManipulator     = new MouseWheelManipulator(transformAdapter);

                var gridAdapter = new D2dGridAdapter();
                gridAdapter.Enabled = false;
                gridAdapter.Visible = true;

                var scrollbarAdapter = new ScrollbarAdapter(transformAdapter, canvasAdapter);

                var hoverAdapter = new HoverAdapter();
                hoverAdapter.HoverStarted += control_HoverStarted;
                hoverAdapter.HoverStopped += control_HoverStopped;

                var annotationAdaptor =                      // display annotations under diagram
                                        new D2dAnnotationAdapter(m_diagramTheme);

                var statechartAdapter = new StatechartGraphAdapter(m_statechartRenderer, transformAdapter);

                var statechartStateEditAdapter =
                    new D2dGraphNodeEditAdapter <StateBase, Transition, BoundaryRoute>(m_statechartRenderer, statechartAdapter, transformAdapter);

                var statechartTransitionEditAdapter =
                    new D2dGraphEdgeEditAdapter <StateBase, Transition, BoundaryRoute>(m_statechartRenderer, statechartAdapter, transformAdapter);

                var mouseLayoutManipulator = new MouseLayoutManipulator(transformAdapter);

                control.Adapt(
                    hoverAdapter,
                    scrollbarAdapter,
                    autoTranslateAdapter,
                    new RectangleDragSelector(),
                    transformAdapter,
                    viewingAdapter,
                    canvasAdapter,
                    mouseTransformManipulator,
                    mouseWheelManipulator,
                    new KeyboardGraphNavigator <StateBase, Transition, BoundaryRoute>(),
                    gridAdapter,
                    annotationAdaptor,
                    statechartAdapter,
                    statechartStateEditAdapter,
                    statechartTransitionEditAdapter,
                    new SelectionAdapter(),
                    mouseLayoutManipulator,
                    new LabelEditAdapter(),
                    new DragDropAdapter(m_statusService),
                    new ContextMenuAdapter(m_commandService, m_contextMenuCommandProviders)
                    );

                control.ResumeLayout();

                // associate the control with the data; several of the adapters need the
                //  control for viewing, layout and calculating bounds.
                var viewingContext = node.Cast <ViewingContext>();
                viewingContext.Control = control;

                var boundsValidator = node.Cast <BoundsValidator>();
                boundsValidator.StatechartRenderer = m_statechartRenderer;

                statechartDocument = node.Cast <Document>();
                string fileName    = Path.GetFileName(filePath);
                var    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;

                statechartDocument.ControlInfo = controlInfo;
                statechartDocument.Uri         = uri;

                // now that the data is complete, initialize the rest of the extensions to the Dom data;
                //  this is needed for adapters such as validators, which may not be referenced anywhere
                //  but still need to be instantiated.
                node.InitializeExtensions();

                // set control's context to main editing context
                var context = node.Cast <EditingContext>();
                control.Context = context;

                m_controlHostService.RegisterControl(control, controlInfo, this);
            }

            return(statechartDocument);
        }
Example #34
0
File: Editor.cs Project: zparr/ATF
        /// <summary>
        /// Opens or creates a document at the given URI. Create an AdaptableControl with control adapters for viewing state machine.
        /// Handles application data persistence.</summary>
        /// <param name="uri">Document URI</param>
        /// <returns>Document, or null if the document couldn't be opened or created</returns>
        public IDocument Open(Uri uri)
        {
            DomNode node     = null;
            string  filePath = uri.LocalPath;
            string  fileName = Path.GetFileName(filePath);

            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(m_schemaLoader);
                    node = reader.Read(stream, uri);
                }
            }
            else
            {
                // create new document by creating a Dom node of the root type defined by the schema
                node = new DomNode(Schema.fsmType.Type, Schema.fsmRootElement);
                // create an empty root prototype folder
                node.SetChild(
                    Schema.fsmType.prototypeFolderChild,
                    new DomNode(Schema.prototypeFolderType.Type));
            }

            Document document = null;

            if (node != null)
            {
                // set up the AdaptableControl for editing FSMs
                var control = new D2dAdaptableControl();
                control.SuspendLayout();

                control.BackColor = SystemColors.ControlLight;
                control.AllowDrop = true;

                var transformAdapter = new TransformAdapter(); // required by several of the other adapters
                transformAdapter.UniformScale = true;
                transformAdapter.MinScale     = new PointF(0.25f, 0.25f);
                transformAdapter.MaxScale     = new PointF(4, 4);

                var viewingAdapter = new ViewingAdapter(transformAdapter); // implements IViewingContext for framing or ensuring that items are visible

                var canvasAdapter = new CanvasAdapter();                   // implements a bounded canvas to limit scrolling

                var autoTranslateAdapter =                                 // implements auto translate when the user drags out of control's client area
                                           new AutoTranslateAdapter(transformAdapter);
                var mouseTransformManipulator =                            // implements mouse drag translate and scale
                                                new MouseTransformManipulator(transformAdapter);
                var mouseWheelManipulator =                                // implements mouse wheel scale
                                            new MouseWheelManipulator(transformAdapter);
                var scrollbarAdapter =                                     // adds scroll bars to control, driven by canvas and transform
                                       new ScrollbarAdapter(transformAdapter, canvasAdapter);

                var hoverAdapter = new HoverAdapter(); // add hover events over pickable items
                hoverAdapter.HoverStarted += control_HoverStarted;
                hoverAdapter.HoverStopped += control_HoverStopped;

                var annotationAdaptor = new D2dAnnotationAdapter(m_theme); // display annotations under diagram

                var fsmAdapter =                                           // adapt control to allow binding to graph data
                                 new D2dGraphAdapter <State, Transition, NumberedRoute>(m_fsmRenderer, transformAdapter);

                var fsmStateEditAdapter = // adapt control to allow state editing
                                          new D2dGraphNodeEditAdapter <State, Transition, NumberedRoute>(m_fsmRenderer, fsmAdapter, transformAdapter);

                var fsmTransitionEditAdapter = // adapt control to allow transition
                                               new D2dGraphEdgeEditAdapter <State, Transition, NumberedRoute>(m_fsmRenderer, fsmAdapter, transformAdapter);

                var mouseLayoutManipulator = new MouseLayoutManipulator(transformAdapter);

                // apply adapters to control; ordering is from back to front, that is, the first adapter
                //  will be conceptually underneath all the others. Mouse and keyboard events are fed to
                //  the adapters in the reverse order, so it all makes sense to the user.
                control.Adapt(
                    hoverAdapter,
                    scrollbarAdapter,
                    autoTranslateAdapter,
                    new RectangleDragSelector(),
                    transformAdapter,
                    viewingAdapter,
                    canvasAdapter,
                    mouseTransformManipulator,
                    mouseWheelManipulator,
                    new KeyboardGraphNavigator <State, Transition, NumberedRoute>(),
                    //new GridAdapter(),
                    annotationAdaptor,
                    fsmAdapter,
                    fsmStateEditAdapter,
                    fsmTransitionEditAdapter,
                    new LabelEditAdapter(),
                    new SelectionAdapter(),
                    mouseLayoutManipulator,
                    new DragDropAdapter(m_statusService),
                    new ContextMenuAdapter(m_commandService, m_contextMenuCommandProviders)
                    );

                control.ResumeLayout();

                // associate the control with the viewing context; other adapters use this
                //  adapter for viewing, layout and calculating bounds.
                ViewingContext viewingContext = node.Cast <ViewingContext>();
                viewingContext.Control = control;

                // set document URI
                document = node.As <Document>();
                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;

                document.ControlInfo = controlInfo;
                document.Uri         = uri;

                // now that the data is complete, initialize the rest of the extensions to the Dom data;
                //  this is needed for adapters such as validators, which may not be referenced anywhere
                //  but still need to be initialized.
                node.InitializeExtensions();

                // set control's context to main editing context
                EditingContext editingContext = node.Cast <EditingContext>();
                control.Context = editingContext;

                // show the FSM control
                m_controlHostService.RegisterControl(control, controlInfo, this);
            }

            return(document);
        }
Example #35
0
        public void TestGetChild()
        {
            DomNodeType type = new DomNodeType("type");
            ChildInfo childInfo = new ChildInfo("child", type);
            type.Define(childInfo);

            DomNode parent = new DomNode(type);
            DomNode child = new DomNode(type);
            parent.SetChild(childInfo, child);
            Assert.AreSame(parent.GetChild(childInfo), child);
            Assert.Throws<InvalidOperationException>(delegate { parent.GetChildList(childInfo); });
        }
Example #36
0
        /// <summary>
        /// Reads the node specified by the child metadata</summary>
        /// <param name="nodeInfo">Child metadata for node</param>
        /// <param name="reader">XML reader</param>
        /// <returns>DomNode specified by the child metadata</returns>
        protected virtual DomNode ReadElement(ChildInfo nodeInfo, XmlReader reader)
        {
            // handle polymorphism, if necessary
            DomNodeType type = null;
            var substitutionGroupRule = nodeInfo.Rules.OfType<SubstitutionGroupChildRule>().FirstOrDefault();
            if (substitutionGroupRule != null)
            {
                foreach (var sub in substitutionGroupRule.Substitutions)
                {
                    if (sub.Name == reader.LocalName)
                    {
                        type = sub.Type;
                        break;
                    }
                }

                // Fallback to non-substituted version (for example loading an old schema).
                if (type == null)
                    type = GetChildType(nodeInfo.Type, reader);

                if (type == null)
                    throw new InvalidOperationException("Could not match substitution group for child " + nodeInfo.Name);
            }
            else
            {
                type = GetChildType(nodeInfo.Type, reader);
            }

            int index = type.Name.LastIndexOf(':');
            string typeNS = type.Name.Substring(0, index);

            DomNode node = new DomNode(type, nodeInfo);

            // read attributes
            while (reader.MoveToNextAttribute())
            {
                if (reader.Prefix == string.Empty ||
                    reader.LookupNamespace(reader.Prefix) == typeNS)
                {
                    AttributeInfo attributeInfo = type.GetAttributeInfo(reader.LocalName);
                    if (attributeInfo != null)
                    {
                        ReadAttribute(node, attributeInfo, reader.Value);
                    }
                }
            }

            // add node to map if it has an id
            if (node.Type.IdAttribute != null)
            {
                string id = node.GetId();
                if (!string.IsNullOrEmpty(id))
                    m_nodeDictionary[id] = node; // don't Add, in case there are multiple DomNodes with the same id
            }

            reader.MoveToElement();

            if (!reader.IsEmptyElement)
            {
                // read child elements
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        // look up metadata for this element
                        ChildInfo childInfo = type.GetChildInfo(reader.LocalName);
                        if (childInfo == null)
                        {
                            // Try and get substitution group
                            childInfo = GetSubsitutionGroup(type, reader.LocalName);
                        }

                        if (childInfo != null)
                        {
                            DomNode childNode = ReadElement(childInfo, reader);
                            if (childNode != null)
                            {
                                // childNode is fully populated sub-tree
                                if (childInfo.IsList)
                                {
                                    node.GetChildList(childInfo).Add(childNode);
                                }
                                else
                                {
                                    node.SetChild(childInfo, childNode);
                                }
                            }
                        }
                        else
                        {
                            // try reading as an attribute
                            AttributeInfo attributeInfo = type.GetAttributeInfo(reader.LocalName);
                            if (attributeInfo != null)
                            {
                                reader.MoveToElement();

                                if (!reader.IsEmptyElement)
                                {
                                    // read element text
                                    while (reader.Read())
                                    {
                                        if (reader.NodeType == XmlNodeType.Text)
                                        {
                                            ReadAttribute(node, attributeInfo, reader.Value);                                            
                                            // skip child elements, as this is an attribute value
                                            reader.Skip();
                                            break;
                                        }
                                        if (reader.NodeType == XmlNodeType.EndElement)
                                        {
                                            break;
                                        }
                                    }

                                    reader.MoveToContent();
                                }
                            }
                            else
                            {
                                    // skip unrecognized element
                                    reader.Skip();
                                    // if that takes us to the end of the enclosing element, break
                                    if (reader.NodeType == XmlNodeType.EndElement)
                                        break;
                            }
                        }
                    }
                    else if (reader.NodeType == XmlNodeType.Text)
                    {
                        AttributeInfo attributeInfo = type.GetAttributeInfo(string.Empty);
                        if (attributeInfo != null)
                        {
                            ReadAttribute(node, attributeInfo, reader.Value);                                                      
                        }
                    }
                    else if (reader.NodeType == XmlNodeType.EndElement)
                    {
                        break;
                    }
                }
            }

            reader.MoveToContent();

            return node;
        }
Example #37
0
        public void TestRemoveFromParent()
        {
            DomNodeType type = new DomNodeType("type");
            ChildInfo childInfo = new ChildInfo("child", type);
            type.Define(childInfo);
            DomNode parent = new DomNode(type);
            DomNode child = new DomNode(type);
            parent.SetChild(childInfo, child);
            child.RemoveFromParent();
            Assert.Null(parent.GetChild(childInfo));
            Assert.Null(child.Parent);

            // Make sure the removed child has a null Parent. http://tracker.ship.scea.com/jira/browse/WWSATF-1336
            parent.SetChild(childInfo, child);
            DomNode newChild = new DomNode(type);
            parent.SetChild(childInfo, newChild);
            Assert.Null(child.Parent);
            Assert.True(newChild.Parent == parent);
        }
Example #38
0
        /// <summary>
        /// Inserts the data object into the context</summary>
        /// <param name="insertingObject">Data to insert</param>
        public void Insert(object insertingObject)
        {
            IDataObject dataObject = (IDataObject)insertingObject;

            object[] items = dataObject.GetData(typeof(object[])) as object[];
            if (items == null || items.Length == 0)
            {
                return;
            }

            IEnumerable <DomNode> childNodes = items.AsIEnumerable <DomNode>();
            // if no items are parented, then we should clone the items, which must be from the clipboard
            bool fromScrap = true;

            foreach (DomNode child in childNodes)
            {
                if (child.Parent != null)
                {
                    fromScrap = false;
                    break;
                }
            }
            if (fromScrap)
            {
                childNodes = DomNode.Copy(childNodes);
                // inited extensions for copied DomNodes
                foreach (DomNode child in childNodes)
                {
                    child.InitializeExtensions();
                }
            }

            DomNode parent = m_insertionParent.As <DomNode>();

            if (parent != null)
            {
                foreach (DomNode child in childNodes)
                {
                    ChildInfo childInfo = GetChildInfo(parent, child.Type);
                    if (childInfo != null)
                    {
                        if (childInfo.IsList)
                        {
                            IList <DomNode> list = parent.GetChildList(childInfo);
                            list.Add(child);
                        }
                        else
                        {
                            parent.SetChild(childInfo, child);
                        }
                    }
                }
            }
            else
            {
                EmptyRef emptyRef = m_insertionParent as EmptyRef;
                if (emptyRef != null)
                {
                    foreach (DomNode child in childNodes)
                    {
                        UIRef uiRef = UIRef.New(child.As <UIObject>());
                        emptyRef.Parent.SetChild(emptyRef.ChildInfo, uiRef.DomNode);
                    }
                }
            }
        }
Example #39
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));

            DomNode singleResult = DomNode.Copy(test);
            Assert.True(Equals(singleResult, test));
        }
Example #40
0
        /// <summary>
        /// Sets the child of our adapted DomNode to a new DomNode</summary>
        /// <param name="childInfo">Metadata to indicate the child</param>
        /// <param name="value">Any IAdaptable, such as DomNodeAdapter, DomNode, or IAdapter</param>
        protected void SetChild(ChildInfo childInfo, IAdaptable value)
        {
            DomNode child = value.As <DomNode>();

            DomNode.SetChild(childInfo, child);
        }
Example #41
0
        /// <summary>
        /// Opens or creates a document at the given URI. Create an AdaptableControl with control adapters for viewing state machine.
        /// Handles application data persistence.</summary>
        /// <param name="uri">Document URI</param>
        /// <returns>Document, or null if the document couldn't be opened or created</returns>
        public IDocument Open(Uri uri)
        {
            DomNode node = null;
            string filePath = uri.LocalPath;
            string fileName = Path.GetFileName(filePath);

            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(m_schemaLoader);
                    node = reader.Read(stream, uri);
                }
            }
            else
            {
                // create new document by creating a Dom node of the root type defined by the schema
                node = new DomNode(Schema.fsmType.Type, Schema.fsmRootElement);
                // create an empty root prototype folder
                node.SetChild(
                    Schema.fsmType.prototypeFolderChild,
                    new DomNode(Schema.prototypeFolderType.Type));
            }

            Document document = null;
            if (node != null)
            {
                // set up the AdaptableControl for editing FSMs
                var control = new D2dAdaptableControl();
                control.SuspendLayout();

                control.BackColor = SystemColors.ControlLight;
                control.AllowDrop = true;

                var transformAdapter = new TransformAdapter(); // required by several of the other adapters
                transformAdapter.UniformScale = true;
                transformAdapter.MinScale = new PointF(0.25f, 0.25f);
                transformAdapter.MaxScale = new PointF(4, 4);

                var viewingAdapter = new ViewingAdapter(transformAdapter); // implements IViewingContext for framing or ensuring that items are visible

                var canvasAdapter = new CanvasAdapter(); // implements a bounded canvas to limit scrolling

                var autoTranslateAdapter = // implements auto translate when the user drags out of control's client area
                    new AutoTranslateAdapter(transformAdapter);
                var mouseTransformManipulator = // implements mouse drag translate and scale
                    new MouseTransformManipulator(transformAdapter);
                var mouseWheelManipulator = // implements mouse wheel scale
                    new MouseWheelManipulator(transformAdapter);
                var scrollbarAdapter = // adds scroll bars to control, driven by canvas and transform
                    new ScrollbarAdapter(transformAdapter, canvasAdapter);

                var hoverAdapter = new HoverAdapter(); // add hover events over pickable items
                hoverAdapter.HoverStarted += control_HoverStarted;
                hoverAdapter.HoverStopped += control_HoverStopped;

                var annotationAdaptor = new D2dAnnotationAdapter(m_theme); // display annotations under diagram

                var fsmAdapter = // adapt control to allow binding to graph data
                    new D2dGraphAdapter<State, Transition, NumberedRoute>(m_fsmRenderer, transformAdapter);

                var fsmStateEditAdapter = // adapt control to allow state editing
                    new D2dGraphNodeEditAdapter<State, Transition, NumberedRoute>(m_fsmRenderer, fsmAdapter, transformAdapter);

                var fsmTransitionEditAdapter = // adapt control to allow transition
                    new D2dGraphEdgeEditAdapter<State, Transition, NumberedRoute>(m_fsmRenderer, fsmAdapter, transformAdapter);

                var mouseLayoutManipulator = new MouseLayoutManipulator(transformAdapter);

                // apply adapters to control; ordering is from back to front, that is, the first adapter
                //  will be conceptually underneath all the others. Mouse and keyboard events are fed to
                //  the adapters in the reverse order, so it all makes sense to the user.
                control.Adapt(
                    hoverAdapter,
                    scrollbarAdapter,
                    autoTranslateAdapter,
                    new RectangleDragSelector(),
                    transformAdapter,
                    viewingAdapter,
                    canvasAdapter,
                    mouseTransformManipulator,
                    mouseWheelManipulator,
                    new KeyboardGraphNavigator<State, Transition, NumberedRoute>(),
                    //new GridAdapter(),
                    annotationAdaptor,
                    fsmAdapter,
                    fsmStateEditAdapter,
                    fsmTransitionEditAdapter,
                    new LabelEditAdapter(),
                    new SelectionAdapter(),
                    mouseLayoutManipulator,
                    new DragDropAdapter(m_statusService),
                    new ContextMenuAdapter(m_commandService, m_contextMenuCommandProviders)
                    );

                control.ResumeLayout();

                // associate the control with the viewing context; other adapters use this
                //  adapter for viewing, layout and calculating bounds.
                ViewingContext viewingContext = node.Cast<ViewingContext>();
                viewingContext.Control = control;

                // set document URI
                document = node.As<Document>();
                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;

                document.ControlInfo = controlInfo;
                document.Uri = uri;

                // now that the data is complete, initialize the rest of the extensions to the Dom data;
                //  this is needed for adapters such as validators, which may not be referenced anywhere
                //  but still need to be initialized.
                node.InitializeExtensions();

                // set control's context to main editing context
                EditingContext editingContext = node.Cast<EditingContext>();
                control.Context = editingContext;

                // show the FSM control
                m_controlHostService.RegisterControl(control, controlInfo, this);
            }
            
            return document;
        }
Example #42
0
        private DomNode CreatePrototype(IEnumerable<IGameObject> gobs)
        {
            DomNode[] originals = new DomNode[1];

            List<IGameObject> copyList = new List<IGameObject>();
            AABB bound = new AABB();
            foreach (IGameObject gameObject in SelectedGobs)
            {
                IBoundable boundable = gameObject.As<IBoundable>();
                bound.Extend(boundable.BoundingBox);
                Matrix4F world = TransformUtils.ComputeWorldTransform(gameObject);
                originals[0] = gameObject.As<DomNode>();
                DomNode[] copies = DomNode.Copy(originals);
                IGameObject copy = copies[0].As<IGameObject>();
                TransformUtils.SetTransform(copy, world);
                copyList.Add(copy);
            }

            DomNode gobchild = null;
            if (copyList.Count > 1)
            {// create group
                IGame game = m_contextRegistry.GetActiveContext<IGame>();
                IGameObjectGroup gobgroup = game.CreateGameObjectGroup();
                gobgroup.Translation = bound.Center;
                gobgroup.UpdateTransform();
                Matrix4F worldInv = new Matrix4F();
                worldInv.Invert(gobgroup.Transform);
                foreach (IGameObject gob in copyList)
                {
                    Vec3F translate = gob.Translation;
                    worldInv.Transform(ref translate);
                    gob.Translation = translate;
                    gob.UpdateTransform();
                    gobgroup.GameObjects.Add(gob);
                }
                gobchild = gobgroup.As<DomNode>();                
            }
            else
            {
                gobchild = copyList[0].As<DomNode>();                
            }

            gobchild.InitializeExtensions();
            gobchild.As<IGameObject>().Translation = new Vec3F(0, 0, 0);

            DomNode prototype = null;
            if (gobchild != null)
            {
                prototype = new DomNode(Schema.prototypeType.Type, Schema.prototypeRootElement);
                prototype.SetChild(Schema.prototypeType.gameObjectChild, gobchild);
            }
            return prototype;
        }
Example #43
0
        /// <summary>
        /// Opens or creates a document at the given URI.
        /// Creates and configures with control adapters D2dAdaptableControl to display subcircuit</summary>
        /// <param name="uri">Document URI</param>
        /// <returns>Document, or null if the document couldn't be opened or created</returns>
        public IDocument Open(Uri uri)
        {
            DomNode node = null;
            string filePath = uri.LocalPath;

            if (File.Exists(filePath))
            {
                // read existing document using standard XML reader
                using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    CircuitReader reader = new CircuitReader(m_schemaLoader);
                    node = reader.Read(stream, uri);
                }
            }
            else
            {
                // create new document by creating a Dom node of the root type defined by the schema
                node = new DomNode(Schema.circuitDocumentType.Type, Schema.circuitRootElement);
                // create an empty root prototype folder
                node.SetChild(
                    Schema.circuitDocumentType.prototypeFolderChild,
                    new DomNode(Schema.prototypeFolderType.Type));
            }

            CircuitDocument circuitCircuitDocument = null;
            if (node != null)
            {
                // now that the data is complete, initialize all other extensions to the Dom data
                node.InitializeExtensions();

                AdaptableControl control = CreateCircuitControl(node);
                control.AddHelp("https://github.com/SonyWWS/ATF/wiki/Adaptable-Controls".Localize());

                var viewingContext = node.Cast<ViewingContext>();
                viewingContext.Control = control;

                circuitCircuitDocument = node.Cast<CircuitDocument>();
                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;

                circuitCircuitDocument.ControlInfo = controlInfo;
                circuitCircuitDocument.Uri = uri;

                var editingContext = node.Cast<CircuitEditingContext>();
                editingContext.GetLocalBound = GetLocalBound;
                editingContext.GetWorldOffset = GetWorldOffset;
                editingContext.GetTitleHeight = GetTitleHeight;
                editingContext.GetLabelHeight = GetLabelHeight;
                editingContext.GetSubContentOffset = GetSubContentOffset;

                control.Context = editingContext;
                editingContext.SchemaLoader = m_schemaLoader; // schema needed for cut and paste between applications

                m_circuitControlRegistry.RegisterControl(node, control, controlInfo, this);

                // Set the zoom and translation to show the existing items (if any).
                var enumerableContext = editingContext.Cast<IEnumerableContext>();
                if (viewingContext.CanFrame(enumerableContext.Items))
                    viewingContext.Frame(enumerableContext.Items);
            }

            return circuitCircuitDocument;
        }
Example #44
0
        public void TestAddChildAndModifyInTransaction()
        {
            DomNode child = m_root.GetChild(ChildInfo);
            DomNode grandchild = child.GetChild(ChildInfo);
            var greatGrandchild = new DomNode(ChildType, ChildInfo);

            // Add a great-grandchild and then modify it. The attribute changed events should be ignored.
            m_transactionContext.DoTransaction(() =>
            {
                grandchild.SetChild(ChildInfo, greatGrandchild);
                greatGrandchild.SetAttribute(StringAttrInfo, "foo1");
            }, "test transaction 1");

            Assert.IsTrue(m_events.Count == 1);
            CheckChildInsertedEvent(m_events[0], grandchild, greatGrandchild);

            // Make sure the TransactionReporter's state gets cleared for the next transaction.
            m_events.Clear();
            m_transactionContext.DoTransaction(() =>
            {
                grandchild.SetChild(ChildInfo, null);//remove great-grandchild
                greatGrandchild.SetChild(ChildInfo, new DomNode(ChildType));
                grandchild.SetChild(ChildInfo, greatGrandchild);//insert great-grandchild (and its child)
                greatGrandchild.SetAttribute(StringAttrInfo, "foo2");
                greatGrandchild.GetChild(ChildInfo).SetAttribute(StringAttrInfo, "child foo2");
            }, "test transaction 2");
            Assert.IsTrue(m_events.Count == 2);
            CheckChildRemovedEvent(m_events[0], grandchild, greatGrandchild);
            CheckChildInsertedEvent(m_events[1], grandchild, greatGrandchild);

            // This time, make sure that removing the child of a newly inserted tree doesn't generate new events.
            greatGrandchild.RemoveFromParent();
            var great2Grandchild = new DomNode(ChildType);
            greatGrandchild.SetChild(ChildInfo, great2Grandchild);
            m_events.Clear();
            m_transactionContext.DoTransaction(() =>
            {
                grandchild.SetChild(ChildInfo, greatGrandchild);//insert great-grandchild and great2Grandchild
                greatGrandchild.SetAttribute(StringAttrInfo, "foo3");
                great2Grandchild.SetAttribute(StringAttrInfo, "foo3");
                great2Grandchild.RemoveFromParent();
            }, "test transaction 3");
            Assert.IsTrue(m_events.Count == 1);
            CheckChildInsertedEvent(m_events[0], grandchild, greatGrandchild);

            // This time, make sure that removing two children of a newly inserted tree doesn't generate new events.
            grandchild.SetChild(ChildInfo, null);
            greatGrandchild.SetChild(ChildInfo, great2Grandchild);
            var great3Grandchild = new DomNode(ChildType);
            great2Grandchild.SetChild(ChildInfo, great3Grandchild);
            m_events.Clear();
            m_transactionContext.DoTransaction(() =>
            {
                grandchild.SetChild(ChildInfo, greatGrandchild);
                greatGrandchild.SetAttribute(StringAttrInfo, "foo4");
                great2Grandchild.SetAttribute(StringAttrInfo, "foo4");
                great3Grandchild.SetAttribute(StringAttrInfo, "foo4");
                great3Grandchild.RemoveFromParent();
                great2Grandchild.RemoveFromParent();
            }, "test transaction 4");
            Assert.IsTrue(m_events.Count == 1);
            CheckChildInsertedEvent(m_events[0], grandchild, greatGrandchild);

            // Check that removing all the inserted children generates no events.
            grandchild.SetChild(ChildInfo, null);
            greatGrandchild.SetChild(ChildInfo, great2Grandchild);
            great2Grandchild.SetChild(ChildInfo, great3Grandchild);
            m_events.Clear();
            m_transactionContext.DoTransaction(() =>
            {
                grandchild.SetChild(ChildInfo, greatGrandchild);
                greatGrandchild.SetAttribute(StringAttrInfo, "foo5");
                great2Grandchild.SetAttribute(StringAttrInfo, "foo5");
                great3Grandchild.SetAttribute(StringAttrInfo, "foo5");
                great3Grandchild.RemoveFromParent();
                great2Grandchild.RemoveFromParent();
                greatGrandchild.RemoveFromParent();
            }, "test transaction 5");
            Assert.IsTrue(m_events.Count == 0);
        }
Example #45
0
        public void Test()
        {
            XmlSchemaTypeLoader loader = new XmlSchemaTypeLoader();
            loader.SchemaResolver = new ResourceStreamResolver(
                Assembly.GetExecutingAssembly(),
                "UnitTests.Atf/Resources");
            loader.Load("testComplexTypes.xsd");

            DomNodeType abstractType = loader.GetNodeType("test:abstractType");
            Assert.IsTrue(abstractType != null);
            Assert.IsTrue(abstractType.IsAbstract);

            DomNodeType complexType1 = loader.GetNodeType("test:complexType1");
            Assert.IsTrue(complexType1 != null);
            Assert.IsTrue(!complexType1.IsAbstract);
            Assert.IsTrue(complexType1.BaseType == abstractType);
            //Assert.IsTrue(complexType1.FindAnnotation("annotation") != null);
            //Assert.IsTrue(complexType1.FindAnnotation("annotation", "attr1") != null);

            DomNodeType complexType2 = loader.GetNodeType("test:complexType2");
            Assert.IsTrue(complexType2 != null);
            Assert.IsTrue(!complexType2.IsAbstract);
            AttributeInfo attr1 = complexType2.GetAttributeInfo("attr1");
            Assert.IsTrue(attr1 != null);
            Assert.IsTrue(attr1.DefaultValue.Equals(1));
            //Assert.IsTrue(attr1.FindAnnotation("annotation") != null);
            AttributeInfo attr2 = complexType2.GetAttributeInfo("attr2");
            Assert.IsTrue(attr2 != null);
            Assert.IsTrue(attr2.DefaultValue.Equals(2));

            DomNodeType complexType3 = loader.GetNodeType("test:complexType3");
            Assert.IsTrue(complexType3 != null);
            Assert.IsTrue(!complexType3.IsAbstract);
            Assert.IsTrue(complexType3.BaseType == complexType2);
            AttributeInfo attr3 = complexType3.GetAttributeInfo("attr3");
            Assert.IsTrue(attr3 != null);
            ChildInfo elem1 = complexType3.GetChildInfo("elem1");
            Assert.IsTrue(elem1 != null);
            Assert.IsTrue(elem1.Type == complexType1);
            //Assert.IsTrue(elem1.FindAnnotation("annotation") != null);
            ChildInfo elem2 = complexType3.GetChildInfo("elem2");
            Assert.IsTrue(elem2 != null);
            Assert.IsTrue(elem2.Type == complexType1);
            Assert.IsTrue(MinMaxCheck(elem2, 1, 3));
            ChildInfo elem3 = complexType3.GetChildInfo("elem3");
            Assert.IsTrue(elem3 != null); //because a sequence of simple types becomes a sequence of child DomNodes
            attr3 = complexType3.GetAttributeInfo("elem3");
            Assert.IsTrue(attr3 == null); //because a sequence of simple types becomes a sequence of child DomNodes
            DomNode node3 = new DomNode(complexType3);
            DomNode elem3Child1 = new DomNode(elem3.Type);
            AttributeInfo elem3ValueAttributeInfo = elem3.Type.GetAttributeInfo(string.Empty);
            elem3Child1.SetAttribute(elem3ValueAttributeInfo, 1);
            DomNode elem3Child2 = new DomNode(elem3.Type);
            elem3Child2.SetAttribute(elem3ValueAttributeInfo, 1);
            DomNode elem3Child3 = new DomNode(elem3.Type);
            elem3Child3.SetAttribute(elem3ValueAttributeInfo, 1);
            node3.GetChildList(elem3).Add(elem3Child1);
            node3.GetChildList(elem3).Add(elem3Child2);
            node3.GetChildList(elem3).Add(elem3Child3);

            IList<DomNode> node3Children = node3.GetChildList(elem3);
            Assert.IsTrue((int)node3Children[0].GetAttribute(elem3ValueAttributeInfo) == 1);
            Assert.IsTrue((int)node3Children[1].GetAttribute(elem3ValueAttributeInfo) == 1);
            Assert.IsTrue((int)node3Children[2].GetAttribute(elem3ValueAttributeInfo) == 1);

            // Update on 8/16/2011. DomXmlReader would not be able to handle a sequence of elements
            //  of a simple type like this. When reading, each subsequent element's value would be
            //  used to set the attribute on the DomNode, overwriting the previous one. So, since
            //  this behavior of converting more than one element of a simple type into an attribute
            //  array was broken, I want to change this unit test that I wrote and make sequences of
            //  elements of simple types into a sequence of DomNode children with a value attribute.
            //  (A value attribute means an attribute whose name is "".) --Ron
            //ChildInfo elem3 = complexType3.GetChildInfo("elem3");
            //Assert.IsTrue(elem3 == null); //because a sequence of simple types becomes an attribute
            //attr3 = complexType3.GetAttributeInfo("elem3");
            //Assert.IsTrue(attr3 != null); //because a sequence of simple types becomes an attribute
            //DomNode node3 = new DomNode(complexType3);
            //object attr3Obj = node3.GetAttribute(attr3);
            //Assert.IsTrue(
            //    attr3Obj is int &&
            //    (int)attr3Obj == 0); //the default integer
            //node3.SetAttribute(attr3, 1);
            //attr3Obj = node3.GetAttribute(attr3);
            //Assert.IsTrue(
            //    attr3Obj is int &&
            //    (int)attr3Obj == 1);
            //node3.SetAttribute(attr3, new int[] { 1, 2, 3 });
            //attr3Obj = node3.GetAttribute(attr3);
            //Assert.IsTrue(
            //    attr3Obj is int[] &&
            //    ((int[])attr3Obj)[2]==3);
            
            DomNodeType complexType4 = loader.GetNodeType("test:complexType4");
            Assert.IsTrue(complexType4 != null);
            Assert.IsTrue(!complexType4.IsAbstract);
            attr1 = complexType4.GetAttributeInfo("attr1");
            Assert.IsTrue(attr1 != null);
            elem1 = complexType4.GetChildInfo("elem1");
            Assert.IsTrue(elem1 != null);
            Assert.IsTrue(elem1.Type == complexType3);
            Assert.IsTrue(MinMaxCheck(elem1, 1, 1));

            DomNodeType complexType5 = loader.GetNodeType("test:complexType5");
            Assert.IsTrue(complexType5 != null);
            Assert.IsTrue(!complexType5.IsAbstract);
            elem1 = complexType5.GetChildInfo("elem1");
            Assert.IsTrue(elem1 != null);
            Assert.IsTrue(elem1.Type == abstractType);
            Assert.IsTrue(MinMaxCheck(elem1, 1, Int32.MaxValue));

            DomNode node5 = new DomNode(complexType5);
            elem2 = complexType5.GetChildInfo("elem2");
            DomNode node2 = new DomNode(complexType2);
            node5.SetChild(elem2, node2);
            node5.SetChild(elem2, null);
            node3 = new DomNode(complexType3);
            elem3 = complexType5.GetChildInfo("elem3");
            node5.SetChild(elem3, node3);
            //The following should violate xs:choice, but we don't fully support this checking yet.
            //ExceptionTester.CheckThrow<InvalidOperationException>(delegate { node5.AddChild(elem2, node2); });

            DomNodeType complexType6 = loader.GetNodeType("test:complexType6");
            Assert.IsTrue(complexType6 != null);
            Assert.IsTrue(!complexType6.IsAbstract);
            elem1 = complexType6.GetChildInfo("elem1");
            Assert.IsTrue(elem1 != null);
            Assert.IsTrue(elem1.Type == abstractType);
            Assert.IsTrue(MinMaxCheck(elem1, 1, Int32.MaxValue));
            elem2 = complexType6.GetChildInfo("elem2");
            Assert.IsTrue(elem2 != null);
            Assert.IsTrue(elem2.Type == complexType2);
            Assert.IsTrue(MinMaxCheck(elem2, 1, Int32.MaxValue));

            //DomNodeType complexType7 = loader.GetNodeType("test:complexType7");
            //Assert.IsTrue(complexType7 != null);
            //Assert.IsTrue(!complexType7.IsAbstract);
            //AttributeInfo attrSimpleSequence = complexType7.GetAttributeInfo("elemSimpleSequence");
            //Assert.IsTrue(attrSimpleSequence == null); //because a sequence of simple types becomes a sequence of child DomNodes
            //ChildInfo elemSimpleSequence = complexType7.GetChildInfo("elemSimpleSequence");
            //Assert.IsTrue(elemSimpleSequence != null); //because a sequence of simple types becomes a sequence of child DomNodes
            //DomNode node7 = new DomNode(complexType7);
            //object attrObj7 = node7.GetAttribute(attrSimpleSequence);
            //Assert.IsTrue(
            //    attrObj7 is float[] &&
            //    ((float[])attrObj7)[0] == 0 &&
            //    ((float[])attrObj7)[1] == 0 &&
            //    ((float[])attrObj7)[2] == 0); //the default vector
            //float[][] newSequence =
            //{
            //    new float[] {1, 2, 3},
            //    new float[] {4, 5, 6},
            //    new float[] {7, 8, 9}
            //};
            //node7.SetAttribute(attrSimpleSequence, newSequence);
            //attrObj7 = node7.GetAttribute(attrSimpleSequence);
            //Assert.IsTrue(ArraysEqual(attrObj7, newSequence));
        }
Example #46
0
        /// <summary>
        /// Reads the node specified by the child metadata</summary>
        /// <param name="nodeInfo">Child metadata for node</param>
        /// <param name="reader">XML reader</param>
        /// <returns>DomNode specified by the child metadata</returns>
        protected virtual DomNode ReadElement(ChildInfo nodeInfo, XmlReader reader)
        {
            // handle polymorphism, if necessary
            DomNodeType type = null;
            var         substitutionGroupRule = nodeInfo.Rules.OfType <SubstitutionGroupChildRule>().FirstOrDefault();

            if (substitutionGroupRule != null)
            {
                foreach (var sub in substitutionGroupRule.Substitutions)
                {
                    if (sub.Name == reader.LocalName)
                    {
                        type = sub.Type;
                        break;
                    }
                }

                if (type == null)
                {
                    throw new InvalidOperationException("Could not match substitution group for child " + nodeInfo.Name);
                }
            }
            else
            {
                type = GetChildType(nodeInfo.Type, reader);
            }

            int    index  = type.Name.LastIndexOf(':');
            string typeNS = type.Name.Substring(0, index);

            DomNode node = new DomNode(type, nodeInfo);

            // read attributes
            while (reader.MoveToNextAttribute())
            {
                if (reader.Prefix == string.Empty ||
                    reader.LookupNamespace(reader.Prefix) == typeNS)
                {
                    AttributeInfo attributeInfo = type.GetAttributeInfo(reader.LocalName);
                    if (attributeInfo != null)
                    {
                        ReadAttribute(node, attributeInfo, reader.Value);
                    }
                }
            }

            // add node to map if it has an id
            if (node.Type.IdAttribute != null)
            {
                string id = node.GetId();
                if (!string.IsNullOrEmpty(id))
                {
                    m_nodeDictionary[id] = node; // don't Add, in case there are multiple DomNodes with the same id
                }
            }

            reader.MoveToElement();

            if (!reader.IsEmptyElement)
            {
                // read child elements
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        // look up metadata for this element
                        ChildInfo childInfo = type.GetChildInfo(reader.LocalName);
                        if (childInfo == null)
                        {
                            // Try and get substitution group
                            childInfo = GetSubsitutionGroup(type, reader.LocalName);
                        }

                        if (childInfo != null)
                        {
                            DomNode childNode = ReadElement(childInfo, reader);
                            if (childNode != null)
                            {
                                // childNode is fully populated sub-tree
                                if (childInfo.IsList)
                                {
                                    node.GetChildList(childInfo).Add(childNode);
                                }
                                else
                                {
                                    node.SetChild(childInfo, childNode);
                                }
                            }
                        }
                        else
                        {
                            // try reading as an attribute
                            AttributeInfo attributeInfo = type.GetAttributeInfo(reader.LocalName);
                            if (attributeInfo != null)
                            {
                                reader.MoveToElement();

                                if (!reader.IsEmptyElement)
                                {
                                    // read element text
                                    while (reader.Read())
                                    {
                                        if (reader.NodeType == XmlNodeType.Text)
                                        {
                                            ReadAttribute(node, attributeInfo, reader.Value);
                                            // skip child elements, as this is an attribute value
                                            reader.Skip();
                                            break;
                                        }
                                        if (reader.NodeType == XmlNodeType.EndElement)
                                        {
                                            break;
                                        }
                                    }

                                    reader.MoveToContent();
                                }
                            }
                            else
                            {
                                // skip unrecognized element
                                reader.Skip();
                                // if that takes us to the end of the enclosing element, break
                                if (reader.NodeType == XmlNodeType.EndElement)
                                {
                                    break;
                                }
                            }
                        }
                    }
                    else if (reader.NodeType == XmlNodeType.Text)
                    {
                        AttributeInfo attributeInfo = type.GetAttributeInfo(string.Empty);
                        if (attributeInfo != null)
                        {
                            ReadAttribute(node, attributeInfo, reader.Value);
                        }
                    }
                    else if (reader.NodeType == XmlNodeType.EndElement)
                    {
                        break;
                    }
                }
            }

            reader.MoveToContent();

            return(node);
        }
Example #47
0
        public void TestAddChildAndModifyInTransaction()
        {
            DomNode child           = m_root.GetChild(ChildInfo);
            DomNode grandchild      = child.GetChild(ChildInfo);
            var     greatGrandchild = new DomNode(ChildType, ChildInfo);

            // Add a great-grandchild and then modify it. The attribute changed events should be ignored.
            m_transactionContext.DoTransaction(() =>
            {
                grandchild.SetChild(ChildInfo, greatGrandchild);
                greatGrandchild.SetAttribute(StringAttrInfo, "foo1");
            }, "test transaction 1");

            Assert.IsTrue(m_events.Count == 1);
            CheckChildInsertedEvent(m_events[0], grandchild, greatGrandchild);

            // Make sure the TransactionReporter's state gets cleared for the next transaction.
            m_events.Clear();
            m_transactionContext.DoTransaction(() =>
            {
                grandchild.SetChild(ChildInfo, null);            //remove great-grandchild
                greatGrandchild.SetChild(ChildInfo, new DomNode(ChildType));
                grandchild.SetChild(ChildInfo, greatGrandchild); //insert great-grandchild (and its child)
                greatGrandchild.SetAttribute(StringAttrInfo, "foo2");
                greatGrandchild.GetChild(ChildInfo).SetAttribute(StringAttrInfo, "child foo2");
            }, "test transaction 2");
            Assert.IsTrue(m_events.Count == 2);
            CheckChildRemovedEvent(m_events[0], grandchild, greatGrandchild);
            CheckChildInsertedEvent(m_events[1], grandchild, greatGrandchild);

            // This time, make sure that removing the child of a newly inserted tree doesn't generate new events.
            greatGrandchild.RemoveFromParent();
            var great2Grandchild = new DomNode(ChildType);

            greatGrandchild.SetChild(ChildInfo, great2Grandchild);
            m_events.Clear();
            m_transactionContext.DoTransaction(() =>
            {
                grandchild.SetChild(ChildInfo, greatGrandchild);//insert great-grandchild and great2Grandchild
                greatGrandchild.SetAttribute(StringAttrInfo, "foo3");
                great2Grandchild.SetAttribute(StringAttrInfo, "foo3");
                great2Grandchild.RemoveFromParent();
            }, "test transaction 3");
            Assert.IsTrue(m_events.Count == 1);
            CheckChildInsertedEvent(m_events[0], grandchild, greatGrandchild);

            // This time, make sure that removing two children of a newly inserted tree doesn't generate new events.
            grandchild.SetChild(ChildInfo, null);
            greatGrandchild.SetChild(ChildInfo, great2Grandchild);
            var great3Grandchild = new DomNode(ChildType);

            great2Grandchild.SetChild(ChildInfo, great3Grandchild);
            m_events.Clear();
            m_transactionContext.DoTransaction(() =>
            {
                grandchild.SetChild(ChildInfo, greatGrandchild);
                greatGrandchild.SetAttribute(StringAttrInfo, "foo4");
                great2Grandchild.SetAttribute(StringAttrInfo, "foo4");
                great3Grandchild.SetAttribute(StringAttrInfo, "foo4");
                great3Grandchild.RemoveFromParent();
                great2Grandchild.RemoveFromParent();
            }, "test transaction 4");
            Assert.IsTrue(m_events.Count == 1);
            CheckChildInsertedEvent(m_events[0], grandchild, greatGrandchild);

            // Check that removing all the inserted children generates no events.
            grandchild.SetChild(ChildInfo, null);
            greatGrandchild.SetChild(ChildInfo, great2Grandchild);
            great2Grandchild.SetChild(ChildInfo, great3Grandchild);
            m_events.Clear();
            m_transactionContext.DoTransaction(() =>
            {
                grandchild.SetChild(ChildInfo, greatGrandchild);
                greatGrandchild.SetAttribute(StringAttrInfo, "foo5");
                great2Grandchild.SetAttribute(StringAttrInfo, "foo5");
                great3Grandchild.SetAttribute(StringAttrInfo, "foo5");
                great3Grandchild.RemoveFromParent();
                great2Grandchild.RemoveFromParent();
                greatGrandchild.RemoveFromParent();
            }, "test transaction 5");
            Assert.IsTrue(m_events.Count == 0);
        }
Example #48
0
        private DomNode ReadElement(ChildInfo nodeInfo, XmlReader reader)
        {
            // handle polymorphism, if necessary
            var type   = GetChildType(nodeInfo.Type, reader);
            var index  = type.Name.LastIndexOf(':');
            var typeNs = type.Name.Substring(0, index);

            var node = new DomNode(type, nodeInfo);

            // read attributes
            while (reader.MoveToNextAttribute())
            {
                if (reader.Prefix == string.Empty ||
                    reader.LookupNamespace(reader.Prefix) == typeNs)
                {
                    var attributeInfo = type.GetAttributeInfo(reader.LocalName);
                    if (attributeInfo != null)
                    {
                        var valueString = reader.Value;
                        if (attributeInfo.Type.Type == AttributeTypes.Reference)
                        {
                            // save reference so it can be resolved after all nodes have been read
                            m_nodeReferences.Add(new XmlNodeReference(node, attributeInfo, valueString));
                        }
                        else
                        {
                            var value = attributeInfo.Type.Convert(valueString);
                            node.SetAttribute(attributeInfo, value);
                        }
                    }
                }
            }

            // add node to map if it has an id
            if (node.Type.IdAttribute != null)
            {
                var id = node.GetId();
                if (!string.IsNullOrEmpty(id))
                {
                    m_nodeDictionary[id] = node; // don't Add, in case there are multiple DomNodes with the same id
                }
            }

            reader.MoveToElement();

            if (!reader.IsEmptyElement)
            {
                // read child elements
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        // look up metadata for this element
                        var childInfo = type.GetChildInfo(reader.LocalName);
                        if (childInfo != null)
                        {
                            var childNode = ReadElement(childInfo, reader);
                            if (childNode != null)
                            {
                                // childNode is fully populated sub-tree
                                if (childInfo.IsList)
                                {
                                    node.GetChildList(childInfo).Add(childNode);
                                }
                                else
                                {
                                    node.SetChild(childInfo, childNode);
                                }
                            }
                        }
                        else
                        {
                            // try reading as an attribute
                            var attributeInfo = type.GetAttributeInfo(reader.LocalName);
                            if (attributeInfo != null)
                            {
                                reader.MoveToElement();

                                if (!reader.IsEmptyElement)
                                {
                                    // read element text
                                    while (reader.Read())
                                    {
                                        if (reader.NodeType == XmlNodeType.Text)
                                        {
                                            var value = attributeInfo.Type.Convert(reader.Value);
                                            node.SetAttribute(attributeInfo, value);
                                            // skip child elements, as this is an attribute value
                                            reader.Skip();
                                            break;
                                        }
                                        if (reader.NodeType == XmlNodeType.EndElement)
                                        {
                                            break;
                                        }
                                    }

                                    reader.MoveToContent();
                                }
                            }
                            else
                            {
                                // skip unrecognized element
                                reader.Skip();
                                // if that takes us to the end of the enclosing element, break
                                if (reader.NodeType == XmlNodeType.EndElement)
                                {
                                    break;
                                }
                            }
                        }
                    }
                    else if (reader.NodeType == XmlNodeType.Text)
                    {
                        var attributeInfo = type.GetAttributeInfo(string.Empty);
                        if (attributeInfo != null)
                        {
                            var value = attributeInfo.Type.Convert(reader.Value);
                            node.SetAttribute(attributeInfo, value);
                        }
                    }
                    else if (reader.NodeType == XmlNodeType.EndElement)
                    {
                        break;
                    }
                }
            }

            reader.MoveToContent();

            return(node);
        }
Example #49
0
        public void Test()
        {
            XmlSchemaTypeLoader loader = new XmlSchemaTypeLoader();

            loader.SchemaResolver = new ResourceStreamResolver(
                Assembly.GetExecutingAssembly(),
                "UnitTests.Atf/Resources");
            loader.Load("testComplexTypes.xsd");

            DomNodeType abstractType = loader.GetNodeType("test:abstractType");

            Assert.IsTrue(abstractType != null);
            Assert.IsTrue(abstractType.IsAbstract);

            DomNodeType complexType1 = loader.GetNodeType("test:complexType1");

            Assert.IsTrue(complexType1 != null);
            Assert.IsTrue(!complexType1.IsAbstract);
            Assert.IsTrue(complexType1.BaseType == abstractType);
            //Assert.IsTrue(complexType1.FindAnnotation("annotation") != null);
            //Assert.IsTrue(complexType1.FindAnnotation("annotation", "attr1") != null);

            DomNodeType complexType2 = loader.GetNodeType("test:complexType2");

            Assert.IsTrue(complexType2 != null);
            Assert.IsTrue(!complexType2.IsAbstract);
            AttributeInfo attr1 = complexType2.GetAttributeInfo("attr1");

            Assert.IsTrue(attr1 != null);
            Assert.IsTrue(attr1.DefaultValue.Equals(1));
            //Assert.IsTrue(attr1.FindAnnotation("annotation") != null);
            AttributeInfo attr2 = complexType2.GetAttributeInfo("attr2");

            Assert.IsTrue(attr2 != null);
            Assert.IsTrue(attr2.DefaultValue.Equals(2));

            DomNodeType complexType3 = loader.GetNodeType("test:complexType3");

            Assert.IsTrue(complexType3 != null);
            Assert.IsTrue(!complexType3.IsAbstract);
            Assert.IsTrue(complexType3.BaseType == complexType2);
            AttributeInfo attr3 = complexType3.GetAttributeInfo("attr3");

            Assert.IsTrue(attr3 != null);
            ChildInfo elem1 = complexType3.GetChildInfo("elem1");

            Assert.IsTrue(elem1 != null);
            Assert.IsTrue(elem1.Type == complexType1);
            //Assert.IsTrue(elem1.FindAnnotation("annotation") != null);
            ChildInfo elem2 = complexType3.GetChildInfo("elem2");

            Assert.IsTrue(elem2 != null);
            Assert.IsTrue(elem2.Type == complexType1);
            Assert.IsTrue(MinMaxCheck(elem2, 1, 3));
            ChildInfo elem3 = complexType3.GetChildInfo("elem3");

            Assert.IsTrue(elem3 != null); //because a sequence of simple types becomes a sequence of child DomNodes
            attr3 = complexType3.GetAttributeInfo("elem3");
            Assert.IsTrue(attr3 == null); //because a sequence of simple types becomes a sequence of child DomNodes
            DomNode       node3                   = new DomNode(complexType3);
            DomNode       elem3Child1             = new DomNode(elem3.Type);
            AttributeInfo elem3ValueAttributeInfo = elem3.Type.GetAttributeInfo(string.Empty);

            elem3Child1.SetAttribute(elem3ValueAttributeInfo, 1);
            DomNode elem3Child2 = new DomNode(elem3.Type);

            elem3Child2.SetAttribute(elem3ValueAttributeInfo, 1);
            DomNode elem3Child3 = new DomNode(elem3.Type);

            elem3Child3.SetAttribute(elem3ValueAttributeInfo, 1);
            node3.GetChildList(elem3).Add(elem3Child1);
            node3.GetChildList(elem3).Add(elem3Child2);
            node3.GetChildList(elem3).Add(elem3Child3);

            IList <DomNode> node3Children = node3.GetChildList(elem3);

            Assert.IsTrue((int)node3Children[0].GetAttribute(elem3ValueAttributeInfo) == 1);
            Assert.IsTrue((int)node3Children[1].GetAttribute(elem3ValueAttributeInfo) == 1);
            Assert.IsTrue((int)node3Children[2].GetAttribute(elem3ValueAttributeInfo) == 1);

            // Update on 8/16/2011. DomXmlReader would not be able to handle a sequence of elements
            //  of a simple type like this. When reading, each subsequent element's value would be
            //  used to set the attribute on the DomNode, overwriting the previous one. So, since
            //  this behavior of converting more than one element of a simple type into an attribute
            //  array was broken, I want to change this unit test that I wrote and make sequences of
            //  elements of simple types into a sequence of DomNode children with a value attribute.
            //  (A value attribute means an attribute whose name is "".) --Ron
            //ChildInfo elem3 = complexType3.GetChildInfo("elem3");
            //Assert.IsTrue(elem3 == null); //because a sequence of simple types becomes an attribute
            //attr3 = complexType3.GetAttributeInfo("elem3");
            //Assert.IsTrue(attr3 != null); //because a sequence of simple types becomes an attribute
            //DomNode node3 = new DomNode(complexType3);
            //object attr3Obj = node3.GetAttribute(attr3);
            //Assert.IsTrue(
            //    attr3Obj is int &&
            //    (int)attr3Obj == 0); //the default integer
            //node3.SetAttribute(attr3, 1);
            //attr3Obj = node3.GetAttribute(attr3);
            //Assert.IsTrue(
            //    attr3Obj is int &&
            //    (int)attr3Obj == 1);
            //node3.SetAttribute(attr3, new int[] { 1, 2, 3 });
            //attr3Obj = node3.GetAttribute(attr3);
            //Assert.IsTrue(
            //    attr3Obj is int[] &&
            //    ((int[])attr3Obj)[2]==3);

            DomNodeType complexType4 = loader.GetNodeType("test:complexType4");

            Assert.IsTrue(complexType4 != null);
            Assert.IsTrue(!complexType4.IsAbstract);
            attr1 = complexType4.GetAttributeInfo("attr1");
            Assert.IsTrue(attr1 != null);
            elem1 = complexType4.GetChildInfo("elem1");
            Assert.IsTrue(elem1 != null);
            Assert.IsTrue(elem1.Type == complexType3);
            Assert.IsTrue(MinMaxCheck(elem1, 1, 1));

            DomNodeType complexType5 = loader.GetNodeType("test:complexType5");

            Assert.IsTrue(complexType5 != null);
            Assert.IsTrue(!complexType5.IsAbstract);
            elem1 = complexType5.GetChildInfo("elem1");
            Assert.IsTrue(elem1 != null);
            Assert.IsTrue(elem1.Type == abstractType);
            Assert.IsTrue(MinMaxCheck(elem1, 1, Int32.MaxValue));

            DomNode node5 = new DomNode(complexType5);

            elem2 = complexType5.GetChildInfo("elem2");
            DomNode node2 = new DomNode(complexType2);

            node5.SetChild(elem2, node2);
            node5.SetChild(elem2, null);
            node3 = new DomNode(complexType3);
            elem3 = complexType5.GetChildInfo("elem3");
            node5.SetChild(elem3, node3);
            //The following should violate xs:choice, but we don't fully support this checking yet.
            //ExceptionTester.CheckThrow<InvalidOperationException>(delegate { node5.AddChild(elem2, node2); });

            DomNodeType complexType6 = loader.GetNodeType("test:complexType6");

            Assert.IsTrue(complexType6 != null);
            Assert.IsTrue(!complexType6.IsAbstract);
            elem1 = complexType6.GetChildInfo("elem1");
            Assert.IsTrue(elem1 != null);
            Assert.IsTrue(elem1.Type == abstractType);
            Assert.IsTrue(MinMaxCheck(elem1, 1, Int32.MaxValue));
            elem2 = complexType6.GetChildInfo("elem2");
            Assert.IsTrue(elem2 != null);
            Assert.IsTrue(elem2.Type == complexType2);
            Assert.IsTrue(MinMaxCheck(elem2, 1, Int32.MaxValue));

            //DomNodeType complexType7 = loader.GetNodeType("test:complexType7");
            //Assert.IsTrue(complexType7 != null);
            //Assert.IsTrue(!complexType7.IsAbstract);
            //AttributeInfo attrSimpleSequence = complexType7.GetAttributeInfo("elemSimpleSequence");
            //Assert.IsTrue(attrSimpleSequence == null); //because a sequence of simple types becomes a sequence of child DomNodes
            //ChildInfo elemSimpleSequence = complexType7.GetChildInfo("elemSimpleSequence");
            //Assert.IsTrue(elemSimpleSequence != null); //because a sequence of simple types becomes a sequence of child DomNodes
            //DomNode node7 = new DomNode(complexType7);
            //object attrObj7 = node7.GetAttribute(attrSimpleSequence);
            //Assert.IsTrue(
            //    attrObj7 is float[] &&
            //    ((float[])attrObj7)[0] == 0 &&
            //    ((float[])attrObj7)[1] == 0 &&
            //    ((float[])attrObj7)[2] == 0); //the default vector
            //float[][] newSequence =
            //{
            //    new float[] {1, 2, 3},
            //    new float[] {4, 5, 6},
            //    new float[] {7, 8, 9}
            //};
            //node7.SetAttribute(attrSimpleSequence, newSequence);
            //attrObj7 = node7.GetAttribute(attrSimpleSequence);
            //Assert.IsTrue(ArraysEqual(attrObj7, newSequence));
        }
Example #50
0
        /// <summary>
        /// Populates DomNode with data from stream data</summary>
        /// <param name="stream">Stream to read data into</param>
        /// <param name="node">Node to populate</param>
        /// <param name="resolvedUri">URI representing object file</param>
        public static void PopulateDomNode(Stream stream, ref DomNode node, Uri resolvedUri)
        {
            // Parse .obj file
            var obj = new ObjFile();
            obj.Read(stream, resolvedUri);

            if (node == null)
                node = new DomNode(Schema.nodeType.Type);

            // Populate mesh
            var mesh = new DomNode(Schema.meshType.Type);
            mesh.SetAttribute(Schema.meshType.nameAttribute, Path.GetFileName(resolvedUri.LocalPath));

            var vertexArray = new DomNode(Schema.meshType_vertexArray.Type);

            // Populate primitive data
            foreach (Group group in obj.m_groups.Values)
                foreach (FaceSet face in group.FaceSets.Values)
                {
                    var primitive = new DomNode(Schema.vertexArray_primitives.Type);
                    primitive.SetAttribute(Schema.vertexArray_primitives.indicesAttribute, face.Indices.ToArray());
                    primitive.SetAttribute(Schema.vertexArray_primitives.sizesAttribute, face.Sizes.ToArray());
                    primitive.SetAttribute(Schema.vertexArray_primitives.typeAttribute, "POLYGONS");

                    // Populate shader
                    MaterialDef material;
                    obj.m_mtl.Materials.TryGetValue(face.MaterialName, out material);

                    if (material != null)
                    {
                        string texture = null;
                        if (material.TextureName != null)
                            texture = new Uri(resolvedUri, material.TextureName).AbsolutePath;

                        var shader = new DomNode(Schema.shaderType.Type);
                        shader.SetAttribute(Schema.shaderType.nameAttribute, material.Name);
                        shader.SetAttribute(Schema.shaderType.ambientAttribute, material.Ambient);
                        shader.SetAttribute(Schema.shaderType.diffuseAttribute, material.Diffuse);
                        shader.SetAttribute(Schema.shaderType.shininessAttribute, material.Shininess);
                        shader.SetAttribute(Schema.shaderType.specularAttribute, material.Specular);
                        shader.SetAttribute(Schema.shaderType.textureAttribute, texture);

                        primitive.SetChild(Schema.vertexArray_primitives.shaderChild, shader);
                    }

                    // Note: Bindings must be in the order: normal, map1, position
                    DomNode binding;
                    if (face.HasNormals)
                    {
                        binding = new DomNode(Schema.primitives_binding.Type);
                        binding.SetAttribute(Schema.primitives_binding.sourceAttribute, "normal");
                        primitive.GetChildList(Schema.vertexArray_primitives.bindingChild).Add(binding);
                    }

                    if (face.HasTexCoords)
                    {
                        binding = new DomNode(Schema.primitives_binding.Type);
                        binding.SetAttribute(Schema.primitives_binding.sourceAttribute, "map1");
                        primitive.GetChildList(Schema.vertexArray_primitives.bindingChild).Add(binding);
                    }

                    binding = new DomNode(Schema.primitives_binding.Type);
                    binding.SetAttribute(Schema.primitives_binding.sourceAttribute, "position");
                    primitive.GetChildList(Schema.vertexArray_primitives.bindingChild).Add(binding);

                    vertexArray.GetChildList(Schema.meshType_vertexArray.primitivesChild).Add(primitive);
                }

            // Populate array data
            DomNode array;
            if (obj.m_normals.Count > 0)
            {
                array = new DomNode(Schema.vertexArray_array.Type);
                array.SetAttribute(Schema.vertexArray_array.Attribute, obj.m_normals.ToArray());
                array.SetAttribute(Schema.vertexArray_array.countAttribute, obj.m_normals.Count / 3);
                array.SetAttribute(Schema.vertexArray_array.nameAttribute, "normal");
                array.SetAttribute(Schema.vertexArray_array.strideAttribute, 3);

                vertexArray.GetChildList(Schema.meshType_vertexArray.arrayChild).Add(array);
            }

            if (obj.m_texcoords.Count > 0)
            {
                array = new DomNode(Schema.vertexArray_array.Type);
                array.SetAttribute(Schema.vertexArray_array.Attribute, obj.m_texcoords.ToArray());
                array.SetAttribute(Schema.vertexArray_array.countAttribute, obj.m_texcoords.Count / 2);
                array.SetAttribute(Schema.vertexArray_array.nameAttribute, "map1");
                array.SetAttribute(Schema.vertexArray_array.strideAttribute, 2);

                vertexArray.GetChildList(Schema.meshType_vertexArray.arrayChild).Add(array);
            }

            array = new DomNode(Schema.vertexArray_array.Type);
            array.SetAttribute(Schema.vertexArray_array.Attribute, obj.m_positions.ToArray());
            array.SetAttribute(Schema.vertexArray_array.countAttribute, obj.m_positions.Count / 3);
            array.SetAttribute(Schema.vertexArray_array.nameAttribute, "position");
            array.SetAttribute(Schema.vertexArray_array.strideAttribute, 3);

            vertexArray.GetChildList(Schema.meshType_vertexArray.arrayChild).Add(array);

            // Set mesh elements
            mesh.SetChild(Schema.meshType.vertexArrayChild, vertexArray);
            node.SetChild(Schema.nodeType.meshChild, mesh);
        }
Example #51
0
        /// <summary>
        /// Opens or creates a document at the given URI.
        /// Creates and configures with control adapters D2dAdaptableControl to display subcircuit</summary>
        /// <param name="uri">Document URI</param>
        /// <returns>Document, or null if the document couldn't be opened or created</returns>
        public IDocument Open(Uri uri)
        {
            DomNode node     = null;
            string  filePath = uri.LocalPath;

            if (File.Exists(filePath))
            {
                // read existing document using standard XML reader
                using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    CircuitReader reader = new CircuitReader(m_schemaLoader);
                    node = reader.Read(stream, uri);
                }
            }
            else
            {
                // create new document by creating a Dom node of the root type defined by the schema
                node = new DomNode(Schema.circuitDocumentType.Type, Schema.circuitRootElement);
                // create an empty root prototype folder
                node.SetChild(
                    Schema.circuitDocumentType.prototypeFolderChild,
                    new DomNode(Schema.prototypeFolderType.Type));
            }

            CircuitDocument circuitCircuitDocument = null;

            if (node != null)
            {
                // now that the data is complete, initialize all other extensions to the Dom data
                node.InitializeExtensions();

                AdaptableControl control = CreateCircuitControl(node);
                control.AddHelp("https://github.com/SonyWWS/ATF/wiki/Adaptable-Controls".Localize());

                var viewingContext = node.Cast <ViewingContext>();
                viewingContext.Control = control;

                circuitCircuitDocument = node.Cast <CircuitDocument>();
                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;

                circuitCircuitDocument.ControlInfo = controlInfo;
                circuitCircuitDocument.Uri         = uri;

                var editingContext = node.Cast <CircuitEditingContext>();
                editingContext.GetLocalBound       = GetLocalBound;
                editingContext.GetWorldOffset      = GetWorldOffset;
                editingContext.GetTitleHeight      = GetTitleHeight;
                editingContext.GetLabelHeight      = GetLabelHeight;
                editingContext.GetSubContentOffset = GetSubContentOffset;

                control.Context             = editingContext;
                editingContext.SchemaLoader = m_schemaLoader; // schema needed for cut and paste between applications

                m_circuitControlRegistry.RegisterControl(node, control, controlInfo, this);
                SkinService.ApplyActiveSkin(control);
                // Set the zoom and translation to show the existing items (if any).
                var enumerableContext = editingContext.Cast <IEnumerableContext>();
                if (viewingContext.CanFrame(enumerableContext.Items))
                {
                    viewingContext.Frame(enumerableContext.Items);
                }

                //var viewingAdapter = control.As<ViewingAdapter>();
                // enable toggle after initial frame operation.
                //  viewingAdapter.ToggleFramingEnabled = true; // toggle frame/unframe.
            }

            return(circuitCircuitDocument);
        }
Example #52
0
            /// <summary>
            /// Run the copier
            /// </summary>
            /// <param name="domProjectTree">Tree to copy</param>
            /// <param name="domTempTree">Copied tree</param>
            public override void Run(DomNode domProjectTree, DomNode domTempTree)
            {
                var lstToCopy = new List<DomNode>();
                GatherNodeTypes(domTempTree, m_nodeType, lstToCopy);

                foreach (var domNode in lstToCopy)
                {
                    var info = domNode.ChildInfo;
                    if (info.IsList)
                    {
                        domProjectTree.GetChildList(info).Add(domNode);
                    }
                    else
                    {
                        domProjectTree.SetChild(info, domNode);
                    }
                }
            }