internal static bool IsUpstreamOf(this NodeModel node, NodeModel otherNode)
        {
            var gathered = new List<NodeModel>();
            otherNode.AllUpstreamNodes(gathered);

            return gathered.Contains(node);
        }
 public ExportWithUnitsViewModel(ExportWithUnits model, NodeView nodeView)
 {
     exportWithUnitsModel = model;           
     nodeViewModel = nodeView.ViewModel;
     nodeModel = nodeView.ViewModel.NodeModel;
     model.PropertyChanged +=model_PropertyChanged;      
 }
示例#3
0
 internal void CreateManipulator(NodeModel model, DynamoManipulationExtension manipulatorContext)
 {
     var creators = registeredManipulatorCreators.Where(pair => pair.Key.IsInstanceOfType(model)).SelectMany(pair => pair.Value);
     activeManipulators[model.GUID] = new CompositeManipulator(
         creators.Select(x => x.Create(model, manipulatorContext)).
         Where(x => x != null).ToList());
 }
示例#4
0
 public void Setup()
 {
     m_Model = new NodeModel(1,
                             2.0,
                             3.0,
                             Angle.For45Degrees);
 }
示例#5
0
 /// <summary>
 /// Validates the watch content with the source nodes output.
 /// </summary>
 /// <param name="watch">WatchViewModel of the watch node</param>
 /// <param name="sourceNode">NodeModel for source to watch node</param>
 public void AssertWatchContent(WatchViewModel watch, NodeModel sourceNode)
 {
     string var = sourceNode.GetAstIdentifierForOutputIndex(0).Name;
     RuntimeMirror mirror = null;
     Assert.DoesNotThrow(() => mirror = ViewModel.Model.EngineController.GetMirror(var));
     Assert.IsNotNull(mirror);
     AssertWatchContent(watch, mirror.GetData());
 }
示例#6
0
 internal void KillManipulators(NodeModel model)
 {
     IDisposable manipulator;
     if (activeManipulators.TryGetValue(model.GUID, out manipulator))
     {
         manipulator.Dispose();
         activeManipulators.Remove(model.GUID);
     }
 }
示例#7
0
        private ConnectorModel(
            NodeModel start, NodeModel end, int startIndex, int endIndex, Guid guid)
        {
            GUID = guid;
            Start = start.OutPorts[startIndex];

            PortModel endPort = end.InPorts[endIndex];

            Start.Connect(this);
            Connect(endPort);
        }
示例#8
0
        /// <summary>
        /// Factory method to create a connector.  Checks to make sure that the start and end ports are valid, 
        /// otherwise returns null.
        /// </summary>
        /// <param name="start">The port where the connector starts</param>
        /// <param name="end">The port where the connector ends</param>
        /// <param name="startIndex"></param>
        /// <param name="endIndex"></param>
        /// <param name="guid"></param>
        /// <returns>The valid connector model or null if the connector is invalid</returns>
        internal static ConnectorModel Make(
            NodeModel start, NodeModel end, int startIndex, int endIndex, Guid? guid = null)
        {
            if (start != null && end != null && start != end && startIndex >= 0
                && endIndex >= 0 && start.OutPorts.Count > startIndex
                && end.InPorts.Count > endIndex)
            {
                return new ConnectorModel(start, end, startIndex, endIndex, guid ?? Guid.NewGuid());
            }

            return null;
        }
        public INodeManipulator Create(NodeModel node, DynamoManipulationExtension manipulatorContext)
        {
            var dsFunction = node as DSFunction;
            if (dsFunction == null) return null;

            var name = dsFunction.CreationName;

            IEnumerable<INodeManipulatorFactory> creators;
            if (manipulatorCreators.TryGetValue(name, out creators))
            {
                return new CompositeManipulator(creators.Select(x => x.Create(node, manipulatorContext)).ToList());
            }
            return null;
        }
示例#10
0
        /// <summary>
        /// Factory method to create a connector.  Checks to make sure that the start and end ports are valid, 
        /// otherwise returns null.
        /// </summary>
        /// <param name="start">The node having port where the connector starts</param>
        /// <param name="end">The node having port where the connector ends</param>
        /// <param name="startIndex">Port index in <paramref name="start"/></param>
        /// <param name="endIndex">Port index in <paramref name="end"/></param>
        /// <param name="guid">Identifier of the new connector</param>
        /// <returns>The valid connector model or null if the connector is invalid</returns>
        internal static ConnectorModel Make(
            NodeModel start, NodeModel end, int startIndex, int endIndex, Guid? guid = null)
        {
            if (start != null && end != null && start != end && startIndex >= 0
                && endIndex >= 0 && start.OutPorts.Count > startIndex
                && end.InPorts.Count > endIndex)
            {
                return new ConnectorModel(start, end, startIndex, endIndex, guid ?? Guid.NewGuid());
            }

            Debug.WriteLine("Could not create a connector between {0} and {1}.", start.NickName, end.NickName);

            return null;
        }
 private void TryApplyCustomization(NodeModel model, NodeView view, InternalNodeViewCustomization customization)
 {
     try
     {
         var disposable = customization.CustomizeView(model, view);
         view.Unloaded += (s, a) => disposable.Dispose();
     }
     catch (Exception e)
     {
         var message = string.Format(Wpf.Properties.Resources.MessageFailedToApplyCustomization, model.GetType().Name);
         logger.LogError(message);
         logger.Log(e);
     }
 }
示例#12
0
 private NodeController[,] buildNetwork(NodeController[,] map)
 {
     for (int i = 0; i< boardWidth; i++)
     {
         for (int j = 0; j < boardHeight; j++)
         {
             GameObject newNode = Instantiate(nodePrefab, new Vector3(i,j,0f), Quaternion.identity) as GameObject;
             newNode.transform.parent = this.transform;
             Node newNodeView = newNode.GetComponent<Node>();
             NodeModel newNodeModel = new NodeModel(new Vector2(i,j));
             FSMSystem newNodeFSM = configureFSM();
             map[i,j] = new NodeController(newNodeModel, newNodeView, newNodeFSM);
         }
     }
     Utilities.alignGroupCenterToOrigin(transform,nodePrefab,boardWidth,boardHeight);
     return map;
 }
        internal void NavigateTo(NodeModel node)
        {
            if(SelectedNode == node || node == null)
                return;

            SelectedNode = node;

            SummaryLabel.Text = node.Name;
            SummaryLabel.ForeColor = ColorProfile.ObjColors[(int)node.ObjType];

            if (SelectedNode.XNode.External)
                DetailsLabel.Text = "Not XRayed";
            else
                DetailsLabel.Text = "";

            SubnodesView.Items.Clear();

            foreach (var subnode in node.Nodes.OrderBy(n => n.Name).OrderBy(n => (int) n.ObjType))
                SubnodesView.Items.Add(new SubnodeItem(subnode));

            SubnodesView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
        }
示例#14
0
        /// <summary>
        /// If all nodes that the node outputs to are in scopes list. I.e.,
        /// </summary>
        /// <param name="node"></param>
        /// <param name="scopes"></param>
        /// <returns></returns>
        private bool IsNodeInScope(NodeModel node, IEnumerable<NodeModel> scopes)
        {
            if (node is Symbol)
            {
                return false;
            }

            foreach (var index in Enumerable.Range(0, node.OutPorts.Count))
            {
                HashSet<Tuple<int, NodeModel>> outputTuples = null;
                if (!node.TryGetOutput(index, out outputTuples))
                {
                    continue;
                }

                if (!outputTuples.All(t => scopes.Contains(t.Item2)))
                {
                    return false;
                }
            }

            return true;
        }
示例#15
0
 private void RequestRemoveModelsHandler(NodeModel node)
 {
     if (CheckAccess())
     {
         ViewModel.DeleteGeometryForNode(node);
     }
     else
     {
         Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(() => ViewModel.DeleteGeometryForNode(node)));
     }
 }
 static DynElementUpdateDelegate ReEvalOnModified(NodeModel node, Action modifiedAction)
 {
     return delegate
     {
         if (!node.RequiresRecalc && !dynRevitSettings.Controller.Running)
         {
             if (modifiedAction != null)
                 modifiedAction();
             node.RequiresRecalc = true;
         }
     };
 }
示例#17
0
        /// <summary>
        /// <param name="workspace">A <see cref="WorkspaceModel"/>.</param>
        /// This method extracts all models from the workspace and puts them
        /// into the combined graph object, LayoutSubgraphs.First()
        /// <param name="isGroupLayout">True if all the selected models are groups.</param>
        /// <param name="layoutSubgraphs"></param>
        /// <param name="subgraphClusters"></param>
        /// </summary>
        private static void GenerateCombinedGraph(this WorkspaceModel workspace, bool isGroupLayout,
                                                  out List <GraphLayout.Graph> layoutSubgraphs, out List <List <GraphLayout.Node> > subgraphClusters)
        {
            layoutSubgraphs = new List <GraphLayout.Graph>
            {
                new GraphLayout.Graph()
            };
            var combinedGraph = layoutSubgraphs.First();

            subgraphClusters = new List <List <GraphLayout.Node> >();

            if (!isGroupLayout)
            {
                foreach (AnnotationModel group in workspace.Annotations)
                {
                    // Treat a group as a graph layout node/vertex
                    combinedGraph.AddNode(group.GUID, group.Width, group.Height, group.X, group.Y,
                                          group.IsSelected || DynamoSelection.Instance.Selection.Count == 0);
                }
            }

            foreach (NodeModel node in workspace.Nodes)
            {
                if (!isGroupLayout)
                {
                    AnnotationModel group = workspace.Annotations.Where(
                        g => g.Nodes.Contains(node)).ToList().FirstOrDefault();

                    // Do not process nodes within groups
                    if (group == null)
                    {
                        combinedGraph.AddNode(node.GUID, node.Width, node.Height, node.X, node.Y,
                                              node.IsSelected || DynamoSelection.Instance.Selection.Count == 0);
                    }
                }
                else
                {
                    // Process all nodes inside the selection
                    combinedGraph.AddNode(node.GUID, node.Width, node.Height, node.X, node.Y,
                                          node.IsSelected || DynamoSelection.Instance.Selection.Count == 0);
                }
            }

            ///Adding all connectorPins (belonging to all connectors) as graph.nodes to the combined graph.
            foreach (ConnectorModel edge in workspace.Connectors)
            {
                foreach (var pin in edge.ConnectorPinModels)
                {
                    combinedGraph.AddNode(pin.GUID,
                                          pin.Width,
                                          pin.Height,
                                          pin.CenterX,
                                          pin.CenterY,
                                          pin.IsSelected || DynamoSelection.Instance.Selection.Count == 0);
                }
            }

            foreach (ConnectorModel edge in workspace.Connectors)
            {
                if (!isGroupLayout)
                {
                    AnnotationModel startGroup = null, endGroup = null;
                    startGroup = workspace.Annotations.Where(
                        g => g.Nodes.Contains(edge.Start.Owner)).ToList().FirstOrDefault();
                    endGroup = workspace.Annotations.Where(
                        g => g.Nodes.Contains(edge.End.Owner)).ToList().FirstOrDefault();

                    // Treat a group as a node, but do not process edges within a group
                    if (startGroup == null || endGroup == null || startGroup != endGroup)
                    {
                        var startGuid = startGroup == null ? edge.Start.Owner.GUID : startGroup.GUID;
                        var endGuid   = endGroup == null ? edge.End.Owner.GUID : endGroup.GUID;

                        AddConnectorEdgesIncludingPinEdges(combinedGraph, edge, startGuid, endGuid);
                    }
                }
                else
                {
                    AddConnectorEdgesIncludingPinEdges(combinedGraph, edge);
                }
            }

            foreach (NoteModel note in workspace.Notes)
            {
                AnnotationModel group = workspace.Annotations.Where(
                    g => g.Nodes.Contains(note)).ToList().FirstOrDefault();

                GraphLayout.Node nd = null;

                if (!isGroupLayout || group == null)
                {
                    // If note is not part of a group, link to the nearest node in the graph
                    nd = combinedGraph.Nodes.OrderBy(node =>
                                                     Math.Pow(node.X + node.Width / 2 - note.X - note.Width / 2, 2) +
                                                     Math.Pow(node.Y + node.Height / 2 - note.Y - note.Height / 2, 2)).FirstOrDefault();
                }
                else
                {
                    // If note is part of a group, link to the nearest node in the group
                    NodeModel ndm = group.Nodes.OfType <NodeModel>().OrderBy(node =>
                                                                             Math.Pow(node.X + node.Width / 2 - note.X - note.Width / 2, 2) +
                                                                             Math.Pow(node.Y + node.Height / 2 - note.Y - note.Height / 2, 2)).FirstOrDefault();

                    // Skip processing the group if there is no node in the group
                    if (ndm == null)
                    {
                        continue;
                    }

                    // If the nearest point is a node model
                    nd = combinedGraph.FindNode(ndm.GUID);

                    // If the nearest point is a group model
                    nd = nd ?? combinedGraph.FindNode(group.GUID);
                }

                // Otherwise, leave the note unchanged
                if (nd != null)
                {
                    nd.LinkNote(note, note.Width, note.Height);
                }
            }

            if (!isGroupLayout)
            {
                // Add all nodes to one big cluster
                List <GraphLayout.Node> bigcluster = new List <GraphLayout.Node>();
                bigcluster.AddRange(combinedGraph.Nodes);
                subgraphClusters.Add(bigcluster);
            }
            else
            {
                // Each group becomes one cluster
                foreach (AnnotationModel group in DynamoSelection.Instance.Selection.OfType <AnnotationModel>())
                {
                    List <GraphLayout.Node> cluster = new List <GraphLayout.Node>();
                    cluster.AddRange(group.Nodes.OfType <NodeModel>().Select(x => combinedGraph.FindNode(x.GUID)));
                    subgraphClusters.Add(cluster);
                }
            }
        }
示例#18
0
        private ConnectorModel(
            NodeModel start, NodeModel end, int startIndex, int endIndex, Guid guid)
        {
            GUID = guid;
            Start = start.OutPorts[startIndex];

            PortModel endPort = end.InPorts[endIndex];

            Debug.WriteLine("Creating a connector between ports {0}(owner:{1}) and {2}(owner:{3}).",
                start.GUID, Start.Owner == null ? "null" : Start.Owner.NickName, end.GUID, endPort.Owner == null ? "null" : endPort.Owner.NickName);

            Start.Connectors.Add(this);
            Connect(endPort);
        }
示例#19
0
        /// <summary>
        /// Cria um valor compatível para o tipo indicado com base no conteúdo
        /// do modelo deserializado.
        /// </summary>
        /// <param name="type">O tipo do dado esperado.</param>
        /// <param name="node">O modelo deserializado.</param>
        /// <returns>O valor obtido da compatibilização.</returns>
        private object CreateCompatibleValue(Type type, NodeModel node)
        {
            if (node == null)
            {
                return(null);
            }

            if (type == typeof(PropertyCollection))
            {
                return((PropertyCollection)CreateCompatibleValue(typeof(object), node));
            }

            if (type == typeof(NameCollection))
            {
                var target = new NameCollection();
                foreach (var item in node.ChildValues())
                {
                    target.Add(item.Value.ToString());
                }
                return(target);
            }

            if (type == typeof(FieldCollection))
            {
                var target = new FieldCollection();
                foreach (var @object in node.ChildObjects())
                {
                    var field = new Field();
                    CopyNodeProperties(@object, field);
                    target.Add(field);
                }
                return(target);
            }

            if (type == typeof(FieldProperties))
            {
                var properties = new FieldProperties();
                CopyNodeProperties(node, properties);
                return(properties);
            }

            if (type == typeof(LinkCollection))
            {
                var target = new LinkCollection();
                foreach (var item in node.Children())
                {
                    var link = new Link();
                    CopyNodeProperties(item, link);
                    target.Add(link);
                }
                return(target);
            }

            if (type == typeof(EntityActionCollection))
            {
                var target = new EntityActionCollection();
                foreach (var item in node.Children())
                {
                    var action = new EntityAction();
                    CopyNodeProperties(item, action);
                    target.Add(action);
                }
                return(target);
            }

            if (type == typeof(EntityCollection))
            {
                var target = new EntityCollection();
                foreach (var item in node.Children())
                {
                    var entity = new Entity();
                    CopyNodeProperties(item, entity);
                    target.Add(entity);
                }
                return(target);
            }

            if (type == typeof(CaseVariantString))
            {
                var text = (node as ValueModel)?.Value.ToString();
                return(text.ChangeCase(TextCase.PascalCase));
            }

            return(CreateCompatibleValue(node));
        }
示例#20
0
 /// <summary>
 /// NodeDeleted event handler.
 /// </summary>
 /// <param name="node"></param>
 public void NodeDeleted(NodeModel node)
 {
     syncDataManager.DeleteNodes(node.GUID);
 }
示例#21
0
        /// <summary>
        /// Aggregates all upstream geometry for the given node then sends
        /// a message that a visualization is ready
        /// </summary>
        /// <param name="node">The node whose upstream geometry you need.</param>
        /// <returns>A render description containing all upstream geometry.</returns>
        public void RenderUpstream(NodeModel node)
        {
            var rd = new RenderDescription();

            //send back just what the node needs
            var watch = new Stopwatch();

            watch.Start();

            if (node == null)
            {
                //send back everything
                rd = AggregateRenderDescriptions();

                //StripDuplicates(rd);

                OnResultsReadyToVisualize(this, new VisualizationEventArgs(rd, string.Empty));
            }
            else
            {
                //send back renderables for the branch
                var drawables = GetUpstreamDrawableIds(node.Inputs);

                var ids = from viz in dynSettings.Controller.VisualizationManager.Visualizations
                          where drawables.Contains(viz.Key)
                          select viz;

                var keyValuePairs = ids as KeyValuePair <string, RenderDescription>[] ?? ids.ToArray();

                var pts       = keyValuePairs.SelectMany(x => x.Value.Points);
                var lines     = keyValuePairs.SelectMany(x => x.Value.Lines);
                var meshes    = keyValuePairs.SelectMany(x => x.Value.Meshes);
                var xs        = keyValuePairs.SelectMany(x => x.Value.XAxisPoints);
                var ys        = keyValuePairs.SelectMany(x => x.Value.YAxisPoints);
                var zs        = keyValuePairs.SelectMany(x => x.Value.ZAxisPoints);
                var pts_sel   = keyValuePairs.SelectMany(x => x.Value.SelectedPoints);
                var lines_sel = keyValuePairs.SelectMany(x => x.Value.SelectedLines);
                var mesh_sel  = keyValuePairs.SelectMany(x => x.Value.SelectedMeshes);
                var text      = keyValuePairs.SelectMany(x => x.Value.Text);

                rd.Points.AddRange(pts);
                rd.Lines.AddRange(lines);
                rd.Meshes.AddRange(meshes);
                rd.XAxisPoints.AddRange(xs);
                rd.YAxisPoints.AddRange(ys);
                rd.ZAxisPoints.AddRange(zs);
                rd.SelectedPoints.AddRange(pts_sel);
                rd.SelectedLines.AddRange(lines_sel);
                rd.SelectedMeshes.AddRange(mesh_sel);
                rd.Text.AddRange(text);

                //StripDuplicates(rd);

                OnResultsReadyToVisualize(this, new VisualizationEventArgs(rd, node.GUID.ToString()));
            }

            watch.Stop();
            Debug.WriteLine(String.Format("{0} ellapsed for aggregating geometry for watch.", watch.Elapsed));

            //LogVisualizationUpdateData(rd, watch.Elapsed.ToString());
        }
示例#22
0
 void DynamoModel_NodeDeleted(NodeModel node)
 {
     UpdateVisualizations();
 }
示例#23
0
        public override bool RunTest(NodeModel node, EngineController engine, StreamWriter writer)
        {
            bool pass = false;

            var valueMap = new Dictionary <Guid, String>();

            if (node.OutPorts.Count > 0)
            {
                var firstNodeConnectors = node.AllConnectors.ToList(); //Get node connectors
                foreach (ConnectorModel connector in firstNodeConnectors)
                {
                    Guid guid = connector.Start.Owner.GUID;
                    if (!valueMap.ContainsKey(guid))
                    {
                        Object data = connector.Start.Owner.GetValue(0, engine).Data;
                        String val  = data != null?data.ToString() : "null";

                        valueMap.Add(guid, val);
                        writer.WriteLine(guid + " :: " + val);
                        writer.Flush();
                    }
                }
            }

            int numberOfUndosNeeded = Mutate(node);

            Thread.Sleep(100);

            writer.WriteLine("### - Beginning undo");
            for (int iUndo = 0; iUndo < numberOfUndosNeeded; iUndo++)
            {
                DynamoViewModel.UIDispatcher.Invoke(new Action(() =>
                {
                    DynamoModel.UndoRedoCommand undoCommand =
                        new DynamoModel.UndoRedoCommand(DynamoModel.UndoRedoCommand.Operation.Undo);

                    DynamoViewModel.ExecuteCommand(undoCommand);
                }));
                Thread.Sleep(100);
            }
            writer.WriteLine("### - undo complete");
            writer.Flush();

            DynamoViewModel.UIDispatcher.Invoke(new Action(() =>
            {
                DynamoModel.RunCancelCommand runCancel =
                    new DynamoModel.RunCancelCommand(false, false);

                DynamoViewModel.ExecuteCommand(runCancel);
            }));
            while (!DynamoViewModel.HomeSpace.RunSettings.RunEnabled)
            {
                Thread.Sleep(10);
            }

            writer.WriteLine("### - Beginning test of NumberRange");
            if (node.OutPorts.Count > 0)
            {
                try
                {
                    var firstNodeConnectors = node.AllConnectors.ToList();
                    foreach (ConnectorModel connector in firstNodeConnectors)
                    {
                        String valmap  = valueMap[connector.Start.Owner.GUID].ToString();
                        Object data    = connector.Start.Owner.GetValue(0, engine).Data;
                        String nodeVal = data != null?data.ToString() : "null";

                        if (valmap != nodeVal)
                        {
                            writer.WriteLine("!!!!!!!!!!! - test of NumberRange is failed");
                            writer.WriteLine(node.GUID);

                            writer.WriteLine("Was: " + nodeVal);
                            writer.WriteLine("Should have been: " + valmap);
                            writer.Flush();
                            return(pass);
                        }
                    }
                }
                catch (Exception)
                {
                    writer.WriteLine("!!!!!!!!!!! - test of NumberRange is failed");
                    writer.Flush();
                    return(pass);
                }
            }
            writer.WriteLine("### - test of NumberRange complete");
            writer.Flush();

            return(pass = true);
        }
        public OneNodeTopicsView()
        {
            InitializeComponent();
            var click = Observable
                        .FromEventPattern <ItemClickEventArgs>(NodeTopcisList, nameof(NodeTopcisList.ItemClick))
                        .Select(x => x.EventArgs.ClickedItem as TopicModel)
                        .ObserveOnCoreDispatcher()
                        .Subscribe(x => PageStack.Next("Right", "Right", typeof(RepliesAndTopicView), x.Id));
            var collect = Observable.FromEventPattern <TappedRoutedEventArgs>(CollectNode, nameof(CollectNode.Tapped))
                          .SelectMany(x => ApiClient.GetNodeInformation(Node.Name))
                          .Select(html =>
            {
                var regexFav   = new Regex("<a href=\"(.*)\">加入收藏</a>");
                var regexUnFav = new Regex("<a href=\"(.*)\">取消收藏</a>");
                var url        = "";
                if (regexFav.IsMatch(html))
                {
                    url = regexFav.Match(html).Groups[1].Value;
                }
                if (regexUnFav.IsMatch(html))
                {
                    url = regexUnFav.Match(html).Groups[1].Value;
                }
                return(url);
            })
                          .SelectMany(url => ApiClient.OnlyGet($"https://www.v2ex.com{url}"))
                          .ObserveOnCoreDispatcher()
                          .Subscribe(x => Node.IsCollect = Node.IsCollect == "加入收藏" ? "取消收藏" : "加入收藏", ex => { });

            NotifyData.LoadDataTask = async count =>
            {
                var html = await ApiClient.GetTopicsWithPageN(Node.Name, NotifyData.CurrentPage);

                var dom = new HtmlParser().ParseDocument(html);
                if (NotifyData.MaxPage == 0)
                {
                    var header = dom.GetElementById("Main").QuerySelector("div.node_header");
                    Node = new NodeModel
                    {
                        Topics    = Convert.ToInt32(header.QuerySelector("strong").TextContent),
                        IsCollect = header.QuerySelector("a").TextContent,
                        Cover     = header.QuerySelector("img") == null
                            ? "ms-appx:///Assets/default.png"
                            : header.QuerySelector("img").GetAttribute("src"),
                        Title = Node.Title,
                        Name  = Node.Name
                    };
                }

                var topics = dom.GetElementById("TopicsNode").Children.Select(node =>
                {
                    var hrefs = node.QuerySelectorAll("a");
                    var imgs  = node.QuerySelector("img.avatar");
                    var topic = new TopicModel
                    {
                        Title  = hrefs[1].TextContent,
                        Member = new MemberModel
                        {
                            Username = hrefs[2].TextContent,
                            Image    = imgs.GetAttribute("src")
                        },
                        Id = int.Parse(node.ClassName.Split('_').Last())
                    };
                    if (hrefs.Length == 5)
                    {
                        topic.LastUsername = $"最后回复者 :{hrefs[3].TextContent}";
                        topic.Replies      = int.Parse(hrefs[4].TextContent);
                        var last           = node.GetElementsByClassName("topic_info").First().TextContent.Split('•')[1].Trim();
                        if (last.Length > 12)
                        {
                            var timeSpan = DateTime.Now - DateTime.Parse(last.Insert(10, " "));
                            last         = $"{(int) timeSpan.TotalDays}天";
                        }

                        topic.LastReply = $"时间 : {last.Trim()}";
                    }

                    return(topic);
                });
                return(new PagesBaseModel <TopicModel>
                {
                    Pages = Node.Topics % 20 == 0 ? Node.Topics / 20 : Node.Topics / 20 + 1,
                    Entity = topics
                });
            };

            _events = new List <IDisposable> {
                collect, click
            };
        }
示例#25
0
        public override bool RunTest(NodeModel node, EngineController engine, StreamWriter writer)
        {
            bool pass = false;

            var valueMap = new Dictionary <Guid, String>();

            if (node.OutPorts.Count > 0)
            {
                Guid   guid = node.GUID;
                Object data = node.GetValue(0, engine).Data;
                String val  = data != null?data.ToString() : "null";

                valueMap.Add(guid, val);
                writer.WriteLine(guid + " :: " + val);
                writer.Flush();
            }

            int numberOfUndosNeeded = Mutate(node);

            Thread.Sleep(100);

            writer.WriteLine("### - Beginning undo");
            for (int iUndo = 0; iUndo < numberOfUndosNeeded; iUndo++)
            {
                DynamoViewModel.UIDispatcher.Invoke(new Action(() =>
                {
                    DynamoModel.UndoRedoCommand undoCommand =
                        new DynamoModel.UndoRedoCommand(
                            DynamoModel.UndoRedoCommand.Operation.Undo);

                    DynamoViewModel.ExecuteCommand(undoCommand);
                }));
            }
            Thread.Sleep(100);

            writer.WriteLine("### - undo complete");
            writer.Flush();
            writer.WriteLine("### - Beginning re-exec");

            ExecuteAndWait();
            writer.WriteLine("### - re-exec complete");
            writer.Flush();

            writer.WriteLine("### - Beginning readback");

            writer.WriteLine("### - Beginning test of DirectoryPath");

            if (node.OutPorts.Count > 0)
            {
                try
                {
                    string valmap  = valueMap[node.GUID].ToString();
                    object data    = node.GetValue(0, engine).Data;
                    string nodeVal = data != null?data.ToString() : "null";

                    if (valmap != nodeVal)
                    {
                        writer.WriteLine("!!!!!!!!!!! - test of DirectoryPath is failed");
                        writer.WriteLine(node.GUID);

                        writer.WriteLine("Was: " + nodeVal);
                        writer.WriteLine("Should have been: " + valmap);
                        writer.Flush();
                        return(pass);
                    }
                }
                catch (Exception)
                {
                    writer.WriteLine("!!!!!!!!!!! - test of DirectoryPath is failed");
                    writer.Flush();
                    return(pass);
                }
            }
            writer.WriteLine("### - test of DirectoryPath complete");
            writer.Flush();

            return(pass = true);
        }
示例#26
0
        public override bool RunTest(NodeModel node, EngineController engine, StreamWriter writer)
        {
            bool pass = false;

            List <ConnectorModel> firstNodeConnectors = node.AllConnectors.ToList();

            Dictionary <Guid, String> valueMap = new Dictionary <Guid, String>();

            foreach (ConnectorModel connector in firstNodeConnectors)
            {
                if (connector.Start.Owner.GUID != node.GUID)
                {
                    Guid guid = connector.Start.Owner.GUID;
                    if (!valueMap.ContainsKey(guid))
                    {
                        String val = connector.Start.Owner.NickName;
                        valueMap.Add(guid, val);
                        writer.WriteLine(guid + " :: " + val);
                        writer.Flush();
                    }
                }
                else if (connector.End.Owner.GUID != node.GUID)
                {
                    Guid guid = connector.End.Owner.GUID;
                    if (!valueMap.ContainsKey(guid))
                    {
                        String val = connector.End.Owner.NickName;
                        valueMap.Add(guid, val);
                        writer.WriteLine(guid + " :: " + val);
                        writer.Flush();
                    }
                }
            }

            int numberOfUndosNeeded = Mutate(node);

            Thread.Sleep(100);

            IList <NodeModel> nodesAfterMutate = DynamoViewModel.Model.CurrentWorkspace.Nodes;

            if (nodesAfterMutate.Contains(node))
            {
                writer.WriteLine("### - Connector wasn't deleted");
                writer.Flush();
                return(pass);
            }
            else
            {
                writer.WriteLine("### - Connector was deleted");
            }

            for (int iUndo = 0; iUndo < numberOfUndosNeeded; iUndo++)
            {
                DynamoViewModel.UIDispatcher.Invoke(new Action(() =>
                {
                    DynamoModel.UndoRedoCommand undoCommand =
                        new DynamoModel.UndoRedoCommand(
                            DynamoModel.UndoRedoCommand.Operation.Undo);

                    DynamoViewModel.ExecuteCommand(undoCommand);
                }));
            }
            Thread.Sleep(100);

            IList <NodeModel> nodesAfterUndo = DynamoViewModel.Model.CurrentWorkspace.Nodes;

            NodeModel nodeAfterUndo = nodesAfterUndo.FirstOrDefault(t => t.GUID.Equals(node.GUID));

            List <ConnectorModel> firstNodeConnectorsAfterUndo = nodeAfterUndo.AllConnectors.ToList();

            foreach (ConnectorModel connector in firstNodeConnectorsAfterUndo)
            {
                if (connector.Start.Owner.GUID != node.GUID)
                {
                    Guid guid = connector.Start.Owner.GUID;

                    if (!valueMap.ContainsKey(guid))
                    {
                        writer.WriteLine("### - ### - Connector wasn't recreated");
                        writer.Flush();
                        return(pass);
                    }
                    else
                    {
                        writer.WriteLine("### - Connector was recreated");
                        writer.Flush();
                    }
                }
                else if (connector.End.Owner.GUID != node.GUID)
                {
                    Guid guid = connector.End.Owner.GUID;

                    if (!valueMap.ContainsKey(guid))
                    {
                        writer.WriteLine("### - ### - Connector wasn't recreated");
                        writer.Flush();
                        return(pass);
                    }
                    else
                    {
                        writer.WriteLine("### - Connector was recreated");
                        writer.Flush();
                    }
                }
            }
            return(pass = true);
        }
示例#27
0
 protected override void NodeModified(NodeModel node)
 {
     base.NodeModified(node);
     RequestRun();
 }
        protected override IEnumerable<NodeModel> OnGizmoClick(IGizmo gizmoInAction, object hitObject)
        {
            var axis = hitObject as Vector;
            if (null == axis) return null;
            
            if(null == inputNode)
            {
                inputNode = CreateAndConnectInputNode(0, 1);
            }

            return new[] { inputNode };
        }
示例#29
0
        /// <summary>
        /// Creates PortModel.
        /// </summary>
        /// <param name="portType">Type of the Port</param>
        /// <param name="owner">Parent Node</param>
        /// <param name="data">Information about port</param>
        public PortModel(PortType portType, NodeModel owner, PortData data)
        {
            IsConnected = false;
            PortType = portType;
            Owner = owner;

            SetPortData(data);

            MarginThickness = new Thickness(0);
            Height = Math.Abs(data.Height) < 0.001 ? Configurations.PortHeightInPixels : data.Height;
        }
示例#30
0
 /// <summary>
 /// Adds a visualization to the dictionary and adds a handler for node property changes.
 /// </summary>
 /// <param name="kvp"></param>
 private void RegisterNodeForVisualization(NodeModel node)
 {
     Visualizations.Add(node.GUID.ToString(), new RenderDescription());
     node.PropertyChanged += node_PropertyChanged;
 }
示例#31
0
 /// <summary>
 /// Get all objects from a given node which have visualizers associated with them.
 /// </summary>
 /// <param name="node"></param>
 /// <returns></returns>
 public static Dictionary <string, object> GetDrawablesFromNode(NodeModel node)
 {
     return(GetDrawableFromValue(new List <int>(), node.OldValue));
 }
示例#32
0
        /// <summary>
        /// Updates input node by specified amount.
        /// </summary>
        /// <param name="inputNode">Input node</param>
        /// <param name="amount">Amount by which it needs to be modified.</param>
        private static void ModifyInputNode(NodeModel inputNode, double amount)
        {
            if (inputNode == null) return;

            if (Math.Abs(amount) < 0.001) return;

            dynamic uiNode = inputNode;

            uiNode.Value = Math.Round(uiNode.Value + amount, 3);
        }
示例#33
0
 /// <summary>
 /// This is required here to compute the nodes delta state.
 /// This is overriden in HomeWorkspaceViewModel
 /// </summary>
 /// <param name="obj">The object.</param>
 public virtual void OnNodeModified(NodeModel obj)
 {
 }
示例#34
0
 /// <summary>
 /// Checks if the given node has any manipulator attached with it.
 /// </summary>
 /// <param name="node">Input Node</param>
 /// <returns>true if node has any manipulator</returns>
 public bool HasNodeManipulator(NodeModel node)
 {
     IDisposable manipulator;
     return activeManipulators.TryGetValue(node.GUID, out manipulator);
 }
示例#35
0
        /// <summary>
        ///     Now that the portData has been set for the new ports, we recreate the connections we
        ///     so mercilessly destroyed, restoring peace and balance to the world once again.
        /// </summary>
        /// <param name="inportConnections"></param>
        /// <param name="outportConnections"> List of the connections that were killed</param>
        private void LoadAndCreateConnectors(OrderedDictionary inportConnections, OrderedDictionary outportConnections)
        {
            //----------------------------Inputs---------------------------------
            /* Input Port connections are matched only if the name is the same */
            for (int i = 0; i < InPortData.Count; i++)
            {
                string varName = InPortData[i].ToolTipString;
                if (inportConnections.Contains(varName))
                {
                    if (inportConnections[varName] != null)
                    {
                        foreach (var startPortModel in (inportConnections[varName] as List <PortModel>))
                        {
                            NodeModel startNode = startPortModel.Owner;
                            var       connector = ConnectorModel.Make(
                                startNode,
                                this,
                                startPortModel.Index,
                                i);
                        }
                        outportConnections[varName] = null;
                    }
                }
            }

            //----------------------------Outputs--------------------------------

            /*The matching is done in three parts:
             * Step 1:
             *   First, it tries to match the connectors wrt to the defined
             *   variable name. Hence it first checks to see if any of the old
             *   variable names are present. If so, if there were any connectors
             *   presnt then it makes the new connectors. As it iterates through
             *   the new ports, it also finds the ports that didnt exist before
             */
            List <int> undefinedIndices = new List <int>();

            for (int i = 0; i < OutPortData.Count; i++)
            {
                string varName = OutPortData[i].ToolTipString;
                if (outportConnections.Contains(varName))
                {
                    if (outportConnections[varName] != null)
                    {
                        foreach (var endPortModel in (outportConnections[varName] as List <PortModel>))
                        {
                            NodeModel endNode   = endPortModel.Owner;
                            var       connector = ConnectorModel.Make(this, endNode, i, endPortModel.Index);
                        }
                        outportConnections[varName] = null;
                    }
                }
                else
                {
                    undefinedIndices.Add(i);
                }
            }

            /*
             * Step 2:
             *   The second priority is to match the connections to the previous
             *   indices. For all the ports that were not previously defined, it
             *   now checks if that "numbered" port had any connections
             *   previously, ie, if the old third port had 2 connections, then
             *   these would go to the new 3rd port (if it is not a variable that
             *   was defined before)
             */
            for (int i = 0; i < undefinedIndices.Count; i++)
            {
                int index = undefinedIndices[i];
                if (index < outportConnections.Count && outportConnections[index] != null)
                {
                    foreach (PortModel endPortModel in (outportConnections[index] as List <PortModel>))
                    {
                        NodeModel endNode   = endPortModel.Owner;
                        var       connector = ConnectorModel.Make(this, endNode, index, endPortModel.Index);
                    }
                    outportConnections[index] = null;
                    undefinedIndices.Remove(index);
                    i--;
                }
            }

            /*
             * Step 2:
             *   The final step. Now that the priorties are finished, the
             *   function tries to reuse any existing connections by attaching
             *   them to any ports that have not already been given connections
             */
            List <List <PortModel> > unusedConnections =
                outportConnections.Values.Cast <List <PortModel> >()
                .Where(portModelList => portModelList != null)
                .ToList();

            while (undefinedIndices.Count > 0 && unusedConnections.Count != 0)
            {
                foreach (PortModel endPortModel in unusedConnections[0])
                {
                    NodeModel      endNode   = endPortModel.Owner;
                    ConnectorModel connector = ConnectorModel.Make(
                        this,
                        endNode,
                        undefinedIndices[0],
                        endPortModel.Index);
                }
                undefinedIndices.RemoveAt(0);
                unusedConnections.RemoveAt(0);
            }
        }
示例#36
0
        public void BuildValueStringAcceptsEmptyContainerInput()
        {
            var res = NodeModel.PrintValue(FScheme.Value.NewContainer(null), 0, 3, 0, 4);

            Assert.AreEqual("<empty>", res);
        }
示例#37
0
 /// <summary>
 /// Returns whether a node has output which has an associated visualizer.
 /// </summary>
 /// <param name="node"></param>
 /// <returns></returns>
 public static bool IsNodeDrawable(NodeModel node)
 {
     return(GetDrawablesFromNode(node).Count > 0);
 }
示例#38
0
        /// <summary>
        ///     Deserialize a function definition from a given path.  A side effect of this function is that
        ///     the node is added to the dictionary of loadedNodes.
        /// </summary>
        /// <param name="funcDefGuid">The function guid we're currently loading</param>
        /// <param name="controller">Reference to the calling controller</param>
        /// <param name="def">The resultant function definition</param>
        /// <returns></returns>
        private bool GetDefinitionFromPath(Guid funcDefGuid, out FunctionDefinition def)
        {
            var controller = dynSettings.Controller;

            try
            {
                var xmlPath = GetNodePath(funcDefGuid);

                #region read xml file

                var xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlPath);

                string funName     = null;
                string category    = "";
                double cx          = 0;
                double cy          = 0;
                string description = "";
                string version     = "";

                double zoom = 1.0;
                string id   = "";

                // load the header

                // handle legacy workspace nodes called dynWorkspace
                // and new workspaces without the dyn prefix
                XmlNodeList workspaceNodes = xmlDoc.GetElementsByTagName("Workspace");
                if (workspaceNodes.Count == 0)
                {
                    workspaceNodes = xmlDoc.GetElementsByTagName("dynWorkspace");
                }

                foreach (XmlNode node in workspaceNodes)
                {
                    foreach (XmlAttribute att in node.Attributes)
                    {
                        if (att.Name.Equals("X"))
                        {
                            cx = double.Parse(att.Value, CultureInfo.InvariantCulture);
                        }
                        else if (att.Name.Equals("Y"))
                        {
                            cy = double.Parse(att.Value, CultureInfo.InvariantCulture);
                        }
                        else if (att.Name.Equals("zoom"))
                        {
                            zoom = double.Parse(att.Value, CultureInfo.InvariantCulture);
                        }
                        else if (att.Name.Equals("Name"))
                        {
                            funName = att.Value;
                        }
                        else if (att.Name.Equals("Category"))
                        {
                            category = att.Value;
                        }
                        else if (att.Name.Equals("Description"))
                        {
                            description = att.Value;
                        }
                        else if (att.Name.Equals("ID"))
                        {
                            id = att.Value;
                        }
                        else if (att.Name.Equals("Version"))
                        {
                            version = att.Value;
                        }
                    }
                }

                // we have a dyf and it lacks an ID field, we need to assign it
                // a deterministic guid based on its name.  By doing it deterministically,
                // files remain compatible
                if (string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(funName))
                {
                    id = GuidUtility.Create(GuidUtility.UrlNamespace, funName).ToString();
                }

                #endregion

                //DynamoCommands.WriteToLogCmd.Execute("Loading node definition for \"" + funName + "\" from: " + xmlPath);
                dynSettings.Controller.DynamoModel.WriteToLog("Loading node definition for \"" + funName + "\" from: " + xmlPath);

                var ws = new CustomNodeWorkspaceModel(
                    funName, category.Length > 0
                    ? category
                    : BuiltinNodeCategories.SCRIPTING_CUSTOMNODES, description, cx, cy)
                {
                    WatchChanges = false,
                    FileName     = xmlPath,
                    Zoom         = zoom
                };

                def = new FunctionDefinition(Guid.Parse(id))
                {
                    WorkspaceModel = ws
                };

                // load a dummy version, so any nodes depending on this node
                // will find an (empty) identifier on compilation
                FScheme.Expression dummyExpression = FScheme.Expression.NewNumber_E(0);
                controller.FSchemeEnvironment.DefineSymbol(def.FunctionId.ToString(), dummyExpression);

                // set the node as loaded
                this.LoadedCustomNodes.Add(def.FunctionId, def);

                XmlNodeList elNodes = xmlDoc.GetElementsByTagName("Elements");
                XmlNodeList cNodes  = xmlDoc.GetElementsByTagName("Connectors");
                XmlNodeList nNodes  = xmlDoc.GetElementsByTagName("Notes");

                if (elNodes.Count == 0)
                {
                    elNodes = xmlDoc.GetElementsByTagName("dynElements");
                }
                if (cNodes.Count == 0)
                {
                    cNodes = xmlDoc.GetElementsByTagName("dynConnectors");
                }
                if (nNodes.Count == 0)
                {
                    nNodes = xmlDoc.GetElementsByTagName("dynNotes");
                }

                XmlNode elNodesList = elNodes[0];
                XmlNode cNodesList  = cNodes[0];
                XmlNode nNodesList  = nNodes[0];

                #region instantiate nodes

                var badNodes = new List <Guid>();

                foreach (XmlNode elNode in elNodesList.ChildNodes)
                {
                    XmlAttribute typeAttrib          = elNode.Attributes["type"];
                    XmlAttribute guidAttrib          = elNode.Attributes["guid"];
                    XmlAttribute nicknameAttrib      = elNode.Attributes["nickname"];
                    XmlAttribute xAttrib             = elNode.Attributes["x"];
                    XmlAttribute yAttrib             = elNode.Attributes["y"];
                    XmlAttribute lacingAttrib        = elNode.Attributes["lacing"];
                    XmlAttribute isVisAttrib         = elNode.Attributes["isVisible"];
                    XmlAttribute isUpstreamVisAttrib = elNode.Attributes["isUpstreamVisible"];

                    string typeName = typeAttrib.Value;

                    //test the GUID to confirm that it is non-zero
                    //if it is zero, then we have to fix it
                    //this will break the connectors, but it won't keep
                    //propagating bad GUIDs
                    var guid = new Guid(guidAttrib.Value);
                    if (guid == Guid.Empty)
                    {
                        guid = Guid.NewGuid();
                    }

                    string nickname = nicknameAttrib.Value;

                    double x = double.Parse(xAttrib.Value, CultureInfo.InvariantCulture);
                    double y = double.Parse(yAttrib.Value, CultureInfo.InvariantCulture);

                    bool isVisible = true;
                    if (isVisAttrib != null)
                    {
                        isVisible = isVisAttrib.Value == "true" ? true : false;
                    }

                    bool isUpstreamVisible = true;
                    if (isUpstreamVisAttrib != null)
                    {
                        isUpstreamVisible = isUpstreamVisAttrib.Value == "true" ? true : false;
                    }

                    typeName = Dynamo.Nodes.Utilities.PreprocessTypeName(typeName);
                    System.Type type = Dynamo.Nodes.Utilities.ResolveType(typeName);
                    if (null == type)
                    {
                        badNodes.Add(guid);
                        continue;
                    }

                    NodeModel el = dynSettings.Controller.DynamoModel.CreateNodeInstance(type, nickname, guid);

                    if (lacingAttrib != null)
                    {
                        LacingStrategy lacing = LacingStrategy.First;
                        Enum.TryParse(lacingAttrib.Value, out lacing);
                        el.ArgumentLacing = lacing;
                    }

                    el.IsVisible         = isVisible;
                    el.IsUpstreamVisible = isUpstreamVisible;

                    ws.Nodes.Add(el);
                    el.WorkSpace = ws;
                    var node = el;

                    node.X = x;
                    node.Y = y;

                    if (el == null)
                    {
                        return(false);
                    }

                    el.DisableReporting();

                    el.Load(
                        elNode,
                        string.IsNullOrEmpty(version)
                            ? new Version(0, 0, 0, 0)
                            : new Version(version));
                }

                #endregion

                #region instantiate connectors

                foreach (XmlNode connector in cNodesList.ChildNodes)
                {
                    XmlAttribute guidStartAttrib = connector.Attributes[0];
                    XmlAttribute intStartAttrib  = connector.Attributes[1];
                    XmlAttribute guidEndAttrib   = connector.Attributes[2];
                    XmlAttribute intEndAttrib    = connector.Attributes[3];
                    XmlAttribute portTypeAttrib  = connector.Attributes[4];

                    var      guidStart  = new Guid(guidStartAttrib.Value);
                    var      guidEnd    = new Guid(guidEndAttrib.Value);
                    int      startIndex = Convert.ToInt16(intStartAttrib.Value);
                    int      endIndex   = Convert.ToInt16(intEndAttrib.Value);
                    PortType portType   = ((PortType)Convert.ToInt16(portTypeAttrib.Value));

                    //find the elements to connect
                    NodeModel start = null;
                    NodeModel end   = null;

                    if (badNodes.Contains(guidStart) || badNodes.Contains(guidEnd))
                    {
                        continue;
                    }

                    foreach (NodeModel e in ws.Nodes)
                    {
                        if (e.GUID == guidStart)
                        {
                            start = e;
                        }
                        else if (e.GUID == guidEnd)
                        {
                            end = e;
                        }
                        if (start != null && end != null)
                        {
                            break;
                        }
                    }

                    try
                    {
                        var newConnector = ConnectorModel.Make(
                            start, end,
                            startIndex, endIndex,
                            portType);
                        if (newConnector != null)
                        {
                            ws.Connectors.Add(newConnector);
                        }
                    }
                    catch
                    {
                        //DynamoCommands.WriteToLogCmd.Execute(string.Format("ERROR : Could not create connector between {0} and {1}.", start.NickName, end.NickName));
                        dynSettings.Controller.DynamoModel.WriteToLog(string.Format("ERROR : Could not create connector between {0} and {1}.", start.NickName, end.NickName));
                    }
                }

                #endregion

                #region instantiate notes

                if (nNodesList != null)
                {
                    foreach (XmlNode note in nNodesList.ChildNodes)
                    {
                        XmlAttribute textAttrib = note.Attributes[0];
                        XmlAttribute xAttrib    = note.Attributes[1];
                        XmlAttribute yAttrib    = note.Attributes[2];

                        string text = textAttrib.Value;
                        double x    = Convert.ToDouble(xAttrib.Value, CultureInfo.InvariantCulture);
                        double y    = Convert.ToDouble(yAttrib.Value, CultureInfo.InvariantCulture);

                        Guid guid    = Guid.NewGuid();
                        var  command = new DynCmd.CreateNoteCommand(guid, text, x, y, false);
                        dynSettings.Controller.DynamoModel.AddNoteInternal(command, ws);
                    }
                }

                #endregion

                foreach (var e in ws.Nodes)
                {
                    e.EnableReporting();
                }

                def.CompileAndAddToEnvironment(controller.FSchemeEnvironment);

                ws.WatchChanges = true;

                this.OnGetDefinitionFromPath(def);
            }
            catch (Exception ex)
            {
                dynSettings.Controller.DynamoModel.WriteToLog("There was an error opening the workbench.");
                dynSettings.Controller.DynamoModel.WriteToLog(ex);

                if (controller.Testing)
                {
                    Assert.Fail(ex.Message);
                }

                def = null;
                return(false);
            }

            return(true);
        }
 // Use this for initialization
 void Start()
 {
     Model = this.GetComponentInParent <NodeModel>();
 }
示例#40
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            NodeModel node = null;

            var obj  = JObject.Load(reader);
            var type = Type.GetType(obj["$type"].Value <string>());

            // If we can't find this type - try to look in our load from assemblies,
            // but only during testing - this is required during testing because some dlls are loaded
            // using Assembly.LoadFrom using the assemblyHelper - which loads dlls into loadFrom context -
            // dlls loaded with LoadFrom context cannot be found using Type.GetType() - this should
            // not be an issue during normal dynamo use but if it is we can enable this code.
            if (type == null && this.isTestMode == true)
            {
                List <Assembly> resultList;

                var typeName = obj["$type"].Value <string>().Split(',').FirstOrDefault();
                // This assemblyName does not usually contain version information...
                var assemblyName = obj["$type"].Value <string>().Split(',').Skip(1).FirstOrDefault().Trim();
                if (assemblyName != null)
                {
                    if (this.loadedAssemblies.TryGetValue(assemblyName, out resultList))
                    {
                        var matchingTypes = resultList.Select(x => x.GetType(typeName)).ToList();
                        type = matchingTypes.FirstOrDefault();
                    }
                }
            }

            // Check for and attempt to resolve an unknown type before proceeding
            if (type == null)
            {
                // Attempt to resolve the type using `AlsoKnownAs`
                var  unresolvedName = obj["$type"].Value <string>().Split(',').FirstOrDefault();
                Type newType;
                nodeFactory.ResolveType(unresolvedName, out newType);

                // If resolved update the type
                if (newType != null)
                {
                    type = newType;
                }
            }

            // If the id is not a guid, makes a guid based on the id of the node
            var guid = GuidUtility.tryParseOrCreateGuid(obj["Id"].Value <string>());

            var replication = obj["Replication"].Value <string>();

            var inPorts  = obj["Inputs"].ToArray().Select(t => t.ToObject <PortModel>()).ToArray();
            var outPorts = obj["Outputs"].ToArray().Select(t => t.ToObject <PortModel>()).ToArray();

            var    resolver         = (IdReferenceResolver)serializer.ReferenceResolver;
            string assemblyLocation = objectType.Assembly.Location;

            bool remapPorts = true;

            // If type is still null at this point return a dummy node
            if (type == null)
            {
                node = CreateDummyNode(obj, assemblyLocation, inPorts, outPorts);
            }
            // Attempt to create a valid node using the type
            else if (type == typeof(Function))
            {
                var functionId = Guid.Parse(obj["FunctionSignature"].Value <string>());

                CustomNodeDefinition def  = null;
                CustomNodeInfo       info = null;
                bool     isUnresolved     = !manager.TryGetCustomNodeData(functionId, null, false, out def, out info);
                Function function         = manager.CreateCustomNodeInstance(functionId, null, false, def, info);
                node = function;

                if (isUnresolved)
                {
                    function.UpdatePortsForUnresolved(inPorts, outPorts);
                }
            }

            else if (type == typeof(CodeBlockNodeModel))
            {
                var code = obj["Code"].Value <string>();
                CodeBlockNodeModel codeBlockNode = new CodeBlockNodeModel(code, guid, 0.0, 0.0, libraryServices, ElementResolver);
                node = codeBlockNode;

                // If the code block node is in an error state read the extra port data
                // and initialize the input and output ports
                if (node.IsInErrorState)
                {
                    List <string> inPortNames = new List <string>();
                    var           inputs      = obj["Inputs"];
                    foreach (var input in inputs)
                    {
                        inPortNames.Add(input["Name"].ToString());
                    }

                    // NOTE: This could be done in a simpler way, but is being implemented
                    //       in this manner to allow for possible future port line number
                    //       information being available in the file
                    List <int> outPortLineIndexes = new List <int>();
                    var        outputs            = obj["Outputs"];
                    int        outputLineIndex    = 0;
                    foreach (var output in outputs)
                    {
                        outPortLineIndexes.Add(outputLineIndex++);
                    }

                    codeBlockNode.SetErrorStatePortData(inPortNames, outPortLineIndexes);
                }
            }
            else if (typeof(DSFunctionBase).IsAssignableFrom(type))
            {
                var    mangledName        = obj["FunctionSignature"].Value <string>();
                var    priorNames         = libraryServices.GetPriorNames();
                var    functionDescriptor = libraryServices.GetFunctionDescriptor(mangledName);
                string newName;

                // Update the function descriptor if a newer migrated version of the node exists
                if (priorNames.TryGetValue(mangledName, out newName))
                {
                    functionDescriptor = libraryServices.GetFunctionDescriptor(newName);
                }

                // Use the functionDescriptor to try and restore the proper node if possible
                if (functionDescriptor == null)
                {
                    node = CreateDummyNode(obj, assemblyLocation, inPorts, outPorts);
                }
                else
                {
                    if (type == typeof(DSVarArgFunction))
                    {
                        node = new DSVarArgFunction(functionDescriptor);
                        // The node syncs with the function definition.
                        // Then we need to make the inport count correct
                        var varg = (DSVarArgFunction)node;
                        varg.VarInputController.SetNumInputs(inPorts.Count());
                    }
                    else if (type == typeof(DSFunction))
                    {
                        node = new DSFunction(functionDescriptor);
                    }
                }
            }
            else if (type == typeof(DSVarArgFunction))
            {
                var functionId = Guid.Parse(obj["FunctionSignature"].Value <string>());
                node = manager.CreateCustomNodeInstance(functionId);
            }
            else if (type.ToString() == "CoreNodeModels.Formula")
            {
                node = (NodeModel)obj.ToObject(type);
            }
            else
            {
                node = (NodeModel)obj.ToObject(type);

                // if node is an customNode input symbol - assign the element resolver.
                if (node is Nodes.CustomNodes.Symbol)
                {
                    (node as Nodes.CustomNodes.Symbol).ElementResolver = ElementResolver;
                }
                // We don't need to remap ports for any nodes with json constructors which pass ports
                remapPorts = false;
            }

            if (remapPorts)
            {
                RemapPorts(node, inPorts, outPorts, resolver, manager.AsLogger());
            }


            // Cannot set Lacing directly as property is protected
            node.UpdateValue(new UpdateValueParams("ArgumentLacing", replication));
            node.GUID = guid;

            // Add references to the node and the ports to the reference resolver,
            // so that they are available for entities which are deserialized later.
            serializer.ReferenceResolver.AddReference(serializer.Context, node.GUID.ToString(), node);

            foreach (var p in node.InPorts)
            {
                serializer.ReferenceResolver.AddReference(serializer.Context, p.GUID.ToString(), p);
            }

            foreach (var p in node.OutPorts)
            {
                serializer.ReferenceResolver.AddReference(serializer.Context, p.GUID.ToString(), p);
            }

            return(node);
        }
        public override bool RunTest(NodeModel node, EngineController engine, StreamWriter writer)
        {
            bool pass = false;

            var types = LoadAllTypesFromDynamoAssemblies();

            foreach (Type type in types)
            {
                string nodeName = GetName(type);

                var firstNodeConnectors = node.AllConnectors.ToList();

                double coordinatesX = node.X;
                double coordinatesY = node.Y;

                if (!string.IsNullOrEmpty(nodeName))
                {
                    DynamoViewModel.UIDispatcher.Invoke(new Action(() =>
                    {
                        var newNode = type.GetDefaultConstructor <NodeModel>()();

                        DynamoModel.CreateNodeCommand createCommand =
                            new DynamoModel.CreateNodeCommand(
                                newNode, coordinatesX, coordinatesY, false, false);

                        DynamoViewModel.ExecuteCommand(createCommand);
                    }));

                    var valueMap = new Dictionary <Guid, String>();
                    foreach (ConnectorModel connector in firstNodeConnectors)
                    {
                        Guid   guid = connector.Start.Owner.GUID;
                        Object data = connector.Start.Owner.GetValue(0, engine).Data;
                        String val  = data != null?data.ToString() : "null";

                        valueMap.Add(guid, val);
                        writer.WriteLine(guid + " :: " + val);
                        writer.Flush();
                    }

                    int numberOfUndosNeeded = Mutate(node);
                    Thread.Sleep(100);

                    writer.WriteLine("### - Beginning undo");
                    for (int iUndo = 0; iUndo < numberOfUndosNeeded; iUndo++)
                    {
                        DynamoViewModel.UIDispatcher.Invoke(new Action(() =>
                        {
                            DynamoModel.UndoRedoCommand undoCommand =
                                new DynamoModel.UndoRedoCommand(DynamoModel.UndoRedoCommand.Operation.Undo);

                            DynamoViewModel.ExecuteCommand(undoCommand);
                        }));
                    }
                    Thread.Sleep(100);

                    writer.WriteLine("### - undo complete");
                    writer.Flush();

                    DynamoViewModel.UIDispatcher.Invoke(new Action(() =>
                    {
                        DynamoModel.RunCancelCommand runCancel =
                            new DynamoModel.RunCancelCommand(false, false);

                        DynamoViewModel.ExecuteCommand(runCancel);
                    }));
                    while (!DynamoViewModel.HomeSpace.RunSettings.RunEnabled)
                    {
                        Thread.Sleep(10);
                    }

                    writer.WriteLine("### - Beginning test of CustomNode");
                    if (node.OutPorts.Count > 0)
                    {
                        try
                        {
                            NodeModel nodeAfterUndo =
                                DynamoViewModel.Model.CurrentWorkspace.Nodes.FirstOrDefault(
                                    (t) => (t.GUID == node.GUID));

                            if (nodeAfterUndo != null)
                            {
                                var firstNodeConnectorsAfterUndo = nodeAfterUndo.AllConnectors.ToList();
                                foreach (ConnectorModel connector in firstNodeConnectors)
                                {
                                    Guid   guid = connector.Start.Owner.GUID;
                                    Object data = connector.Start.Owner.GetValue(0, engine).Data;
                                    String val  = data != null?data.ToString() : "null";

                                    if (valueMap[guid] != val)
                                    {
                                        writer.WriteLine("!!!!!!!!!!! - test of CustomNode is failed");
                                        writer.WriteLine(node.GUID);

                                        writer.WriteLine("Was: " + val);
                                        writer.WriteLine("Should have been: " + valueMap[guid]);
                                        writer.Flush();
                                        return(pass);
                                    }
                                }
                            }
                        }
                        catch (Exception)
                        {
                            writer.WriteLine("!!!!!!!!!!! - test of CustomNode is failed");
                            writer.Flush();
                            return(pass);
                        }
                    }
                    writer.WriteLine("### - test of CustomNode complete");
                    writer.Flush();
                }
            }
            return(pass = true);
        }
示例#42
0
 /// <summary>
 /// NodeDeleted event handler.
 /// </summary>
 /// <param name="node"></param>
 public void NodeDeleted(NodeModel node)
 {
     syncDataManager.DeleteNodes(node.GUID);
 }
 protected override void NodeModified(NodeModel node)
 {
     base.NodeModified(node);
     RequestRun();
 }
示例#44
0
 public DynamoSlider(NodeModel model)
 {
     nodeModel = model;
 }
示例#45
0
    public NodeModel getTarget(NodeModel current)
    {
        NodeModel target = null;
        if (instructionList[0].direction == "noInstructions")
        {
            return target;
        }
        for (int i = 0; i < instructionList.Length; i++)
        {
            if (instructionList[i].direction == "North")
            {
                if ((current.GetNorth() != null) && (current.GetNorth().getProperty("DeadEnd") == false))
                {
                    if (current.GetNorth().getProperty(instructionList[i].property))
                    {
                        target = current.GetNorth();
                        return target;
                    }
                }
            }
            else if (instructionList[i].direction == "South")
            {
                if ((current.GetSouth() != null) && (current.GetSouth().getProperty("DeadEnd") == false))
                {
                    if (current.GetSouth().getProperty(instructionList[i].property))
                    {
                        target = current.GetSouth();
                        return target;
                    }
                }
            }
            else if (instructionList[i].direction == "East")
            {
                if ((current.GetEast() != null) && (current.GetEast().getProperty("DeadEnd") == false))
                {
                    if (current.GetEast().getProperty(instructionList[i].property))
                    {
                        target = current.GetEast();
                        return target;
                    }
                }
            }
            else if (instructionList[i].direction == "West")
            {
                if ((current.GetWest() != null) && (current.GetWest().getProperty("DeadEnd") == false))
                {
                    if (current.GetWest().getProperty(instructionList[i].property))
                    {
                        target = current.GetWest();
                        return target;
                    }
                }
            }
            else if (instructionList[i].direction == "Current")
            {
                current.CheckIfDeadEnd();
            }
        }

        return target;
    }
示例#46
0
 /// <summary>
 /// Create a set of manipulators for the given node by inspecting its numeric inputs
 /// </summary>
 /// <param name="node"></param>
 /// <param name="manipulatorContext"></param>
 /// <returns></returns>
 public abstract INodeManipulator Create(NodeModel node, DynamoManipulationExtension manipulatorContext);
 public INodeManipulator Create(NodeModel node, DynamoManipulationExtension manipulatorContext)
 {
     return new PointOnCurveManipulator(node as DSFunction, manipulatorContext);
 }
示例#48
0
        protected override AssociativeNode GetFunctionApplication(NodeModel model, List <AssociativeNode> inputAstNodes)
        {
            AssociativeNode rhs;

            string function = Definition.FunctionName;

            switch (Definition.Type)
            {
            case FunctionType.Constructor:
            case FunctionType.StaticMethod:
                if (model.IsPartiallyApplied)
                {
                    var functionNode = new IdentifierListNode
                    {
                        LeftNode  = new IdentifierNode(Definition.ClassName),
                        RightNode = new IdentifierNode(Definition.FunctionName)
                    };
                    rhs = CreateFunctionObject(model, functionNode, inputAstNodes);
                }
                else
                {
                    model.AppendReplicationGuides(inputAstNodes);
                    rhs = AstFactory.BuildFunctionCall(
                        Definition.ClassName,
                        Definition.FunctionName,
                        inputAstNodes);
                }
                break;

            case FunctionType.StaticProperty:

                var staticProp = new IdentifierListNode
                {
                    LeftNode  = new IdentifierNode(Definition.ClassName),
                    RightNode = new IdentifierNode(Definition.FunctionName)
                };
                rhs = staticProp;
                break;

            case FunctionType.InstanceProperty:

                // Only handle getter here. Setter could be handled in CBN.
                if (model.IsPartiallyApplied)
                {
                    var functionNode = new IdentifierListNode
                    {
                        LeftNode  = new IdentifierNode(Definition.ClassName),
                        RightNode = new IdentifierNode(Definition.FunctionName)
                    };
                    rhs = CreateFunctionObject(model, functionNode, inputAstNodes);
                }
                else
                {
                    rhs = new NullNode();
                    if (inputAstNodes != null && inputAstNodes.Count >= 1)
                    {
                        var thisNode = inputAstNodes[0];
                        if (thisNode != null && !(thisNode is NullNode))
                        {
                            var insProp = new IdentifierListNode
                            {
                                LeftNode  = inputAstNodes[0],
                                RightNode = new IdentifierNode(Definition.FunctionName)
                            };
                            rhs = insProp;
                        }
                    }
                }

                break;

            case FunctionType.InstanceMethod:
                if (model.IsPartiallyApplied)
                {
                    var functionNode = new IdentifierListNode
                    {
                        LeftNode  = new IdentifierNode(Definition.ClassName),
                        RightNode = new IdentifierNode(Definition.FunctionName)
                    };
                    rhs = CreateFunctionObject(model, functionNode, inputAstNodes);
                }
                else
                {
                    rhs = new NullNode();
                    model.AppendReplicationGuides(inputAstNodes);

                    if (inputAstNodes != null && inputAstNodes.Count >= 1)
                    {
                        var thisNode = inputAstNodes[0];
                        inputAstNodes.RemoveAt(0);     // remove this pointer

                        if (thisNode != null && !(thisNode is NullNode))
                        {
                            var memberFunc = new IdentifierListNode
                            {
                                LeftNode  = thisNode,
                                RightNode =
                                    AstFactory.BuildFunctionCall(function, inputAstNodes)
                            };
                            rhs = memberFunc;
                        }
                    }
                }

                break;

            default:
                if (model.IsPartiallyApplied)
                {
                    var functionNode = new IdentifierNode(function);
                    rhs = CreateFunctionObject(model, functionNode, inputAstNodes);
                }
                else
                {
                    model.AppendReplicationGuides(inputAstNodes);
                    rhs = AstFactory.BuildFunctionCall(function, inputAstNodes);
                }
                break;
            }

            return(rhs);
        }
示例#49
0
        /// <summary>
        /// Call this method to recursively gather downstream nodes of a given node.
        /// Returns only those nodes that are in RUN state.
        /// </summary>
        /// <param name="node">A NodeModel whose downstream nodes are to be gathered.</param>
        /// <param name="gathered">A list of all downstream nodes.</param>
        /// 
        private static void GetDownstreamNodes(NodeModel node, ICollection<NodeModel> gathered)
        {
            if (gathered.Contains(node) || node.IsFrozen) // Considered this node before, bail.pu
                return;

            gathered.Add(node);

            var sets = node.OutputNodes.Values;
            var outputNodes = sets.SelectMany(set => set.Select(t => t.Item2)).Distinct();
            foreach (var outputNode in outputNodes)
            {
                // Recursively get all downstream nodes.
                GetDownstreamNodes(outputNode, gathered);
            }
        }
        protected override void OnRenderPackagesUpdated(NodeModel node,
            IEnumerable<IRenderPackage> renderPackages)
        {
            var updatedNode = model.CurrentWorkspace.Nodes.FirstOrDefault(n => n.GUID == node.GUID);
            if (updatedNode == null) return;

            var visibleUpstream = new List<NodeModel>();
            watchNode.VisibleUpstreamNodes(visibleUpstream);

            if (!visibleUpstream.Contains(updatedNode))
            {
                return;
            }

            base.OnRenderPackagesUpdated(node, renderPackages);
        }
示例#51
0
        public void BuildValueStringAcceptsNullInput()
        {
            var res = NodeModel.PrintValue(null, 0, 3, 0, 4);

            Assert.AreEqual("<null>", res);
        }
示例#52
0
 /// <summary>
 /// Called when the RequestSilenceNodeModifiedEvents event is emitted from a Node
 /// </summary>
 /// <param name="node">The node itself</param>
 /// <param name="value">A boolean value indicating whether to silence or not</param>
 private void NodeOnRequestSilenceNodeModifiedEvents(NodeModel node, bool value)
 {
     this.silenceNodeModifications = value;
 }
示例#53
0
 /// <summary>
 /// When a node is in freeze state, the node and its dependencies are
 /// deleted from AST
 /// </summary>
 /// <param name="node">The node.</param>
 internal void DeleteFrozenNodesFromAST(NodeModel node)
 {
     HashSet<NodeModel> gathered = new HashSet<NodeModel>();
     node.GetDownstreamNodes(node, gathered);
     foreach (var iNode in gathered)
     {
         syncDataManager.DeleteNodes(iNode.GUID);
     }
 }
示例#54
0
 internal void RegisterNode(NodeModel node)
 {
     profilingData.RegisterNode(node);
 }
示例#55
0
 /// <summary>
 /// Helper method to get the first item from the objects resulted from
 /// this node.
 /// </summary>
 /// <param name="node">Input Node</param>
 /// <returns>Returns the first item of the node.</returns>
 protected static object GetFirstValueFromNode(NodeModel node)
 {
     return(GetElementsFromMirrorData(node.CachedValue).FirstOrDefault());
 }
示例#56
0
 public static GraphElement CreateNode(this INodeBuilder builder, Store store, NodeModel model)
 {
     return(new Node(model, store, builder.GraphView));
 }
 protected VariableInputNodeController(NodeModel model)
 {
     this.model = model;
 }
示例#58
0
文件: File.cs 项目: yaoclee/Dynamo
 protected FileSystemObjectDisposable(NodeModel nodeModel)
 {
     node = nodeModel;
 }
示例#59
0
文件: Node.cs 项目: Greg-Rus/Linker
    private Node nodeView; //Not used yet. Exists to enable controll of the GameObject

    #endregion Fields

    #region Constructors

    public NodeController(NodeModel model, Node view, FSMSystem FSM)
    {
        nodeModel = model;
        nodeView = view;
        nodeFSM = FSM;
    }
示例#60
0
        /// <summary>
        /// Called when a node is disposed and removed from the workspace
        /// </summary>
        /// <param name="node">The node itself</param>
        protected override void DisposeNode(NodeModel node)
        {
            node.RequestSilenceNodeModifiedEvents -= NodeOnRequestSilenceNodeModifiedEvents;

            base.DisposeNode(node);
        }