Beispiel #1
0
        /// <summary>
        /// Load a WorkspaceModel from json. If the WorkspaceModel is a HomeWorkspaceModel
        /// it will be set as the current workspace.
        /// </summary>
        /// <param name="json"></param>
        public static WorkspaceModel LoadWorkspaceFromJson(string json, LibraryServices libraryServices,
            EngineController engineController, DynamoScheduler scheduler, NodeFactory factory,
            bool isTestMode, bool verboseLogging, CustomNodeManager manager)
        {
            var settings = new JsonSerializerSettings
            {
                Error = (sender, args) =>
                {
                    args.ErrorContext.Handled = true;
                    Console.WriteLine(args.ErrorContext.Error);
                },
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                TypeNameHandling = TypeNameHandling.Auto,
                Formatting = Formatting.Indented,
                Converters = new List<JsonConverter>{
                        new ConnectorConverter(),
                        new AnnotationConverter(),
                        new WorkspaceConverter(engineController, scheduler, factory, isTestMode, verboseLogging),
                        new NodeModelConverter(manager, libraryServices),
                    },
                ReferenceResolverProvider = () => { return new IdReferenceResolver(); }
            };

            var result = ReplaceTypeDeclarations(json, true);
            var ws = JsonConvert.DeserializeObject<WorkspaceModel>(result, settings);

            return ws;
        }
        /// <summary>
        /// This method is called by code that intends to start a graph update.
        /// This method is called on the main thread where node collection in a 
        /// WorkspaceModel can be safely accessed.
        /// </summary>
        /// <param name="controller">Reference to an instance of EngineController 
        /// to assist in generating GraphSyncData object for the given set of nodes.
        /// </param>
        /// <param name="workspace">Reference to the WorkspaceModel from which a 
        /// set of updated nodes is computed. The EngineController generates the 
        /// resulting GraphSyncData from this list of updated nodes.</param>
        /// <returns>Returns true if there is any GraphSyncData, or false otherwise
        /// (in which case there will be no need to schedule UpdateGraphAsyncTask 
        /// for execution).</returns>
        /// 
        internal bool Initialize(EngineController controller, WorkspaceModel workspace)
        {
            try
            {
                engineController = controller;
                TargetedWorkspace = workspace;

                ModifiedNodes = ComputeModifiedNodes(workspace);
                graphSyncData = engineController.ComputeSyncData(workspace.Nodes, ModifiedNodes, verboseLogging);
                if (graphSyncData == null)
                    return false;

                // We clear dirty flags before executing the task. If we clear
                // flags after the execution of task, for example in
                // AsyncTask.Completed or in HandleTaskCompletionCore(), as both
                // are executed in the other thread, although some nodes are
                // modified and we request graph execution, but just before
                // computing sync data, the task completion handler jumps in
                // and clear dirty flags. Now graph sync data will be null and
                // graph is in wrong state.
                foreach (var nodeGuid in graphSyncData.NodeIDs)
                {
                    var node = workspace.Nodes.FirstOrDefault(n => n.GUID.Equals(nodeGuid));
                    if (node != null)
                        node.ClearDirtyFlag();
                }

                return true;
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("UpgradeGraphAsyncTask saw: " + e.ToString());
                return false;
            }
        }
Beispiel #3
0
            public WorkspaceComparisonData(WorkspaceModel workspace, EngineController controller)
            {
                Guid = workspace.Guid;
                NodeCount = workspace.Nodes.Count();
                ConnectorCount = workspace.Connectors.Count();
                GroupCount = workspace.Annotations.Count();
                NoteCount = workspace.Notes.Count();
                NodeTypeMap = new Dictionary<Guid, Type>();
                NodeDataMap = new Dictionary<Guid, List<object>>();
                InportCountMap = new Dictionary<Guid, int>();
                OutportCountMap = new Dictionary<Guid, int>();

                foreach (var n in workspace.Nodes)
                {
                    NodeTypeMap.Add(n.GUID, n.GetType());

                    var portvalues = new List<object>();
                    foreach (var p in n.OutPorts)
                    {
                        var value = n.GetValue(p.Index, controller);
                        if (value.IsCollection)
                        {
                            portvalues.Add(GetStringRepOfCollection(value));
                        }
                        else
                        {
                            portvalues.Add(value.StringData);
                        }
                    }
                    
                    NodeDataMap.Add(n.GUID, portvalues);
                    InportCountMap.Add(n.GUID, n.InPorts.Count);
                    OutportCountMap.Add(n.GUID, n.OutPorts.Count);
                }
            }
        internal QueryMirrorDataAsyncTask(QueryMirrorDataParams initParams)
            : base(initParams.Scheduler)
        {
            if (initParams.EngineController == null)
                throw new ArgumentNullException("initParams.EngineController");
            if (string.IsNullOrEmpty(initParams.VariableName))
                throw new ArgumentNullException("initParams.VariableName");

            variableName = initParams.VariableName;
            engineController = initParams.EngineController;
        }
        /// <summary>
        /// This method is called by task creator to associate the trace data with
        /// the current instance of virtual machine. The given WorkspaceModel can
        /// optionally contain saved trace data in a previous execution session. As
        /// a side-effect, this method resets "WorkspaceModel.PreloadedTraceData"
        /// data member to ensure the correctness of the execution flow.
        /// </summary>
        /// <param name="controller">Reference to the EngineController on which the 
        /// loaded trace data should be set.</param>
        /// <param name="workspace">The workspace from which the trace data should 
        /// be retrieved.</param>
        /// <returns>If the given WorkspaceModel contains saved trace data, this 
        /// method returns true, in which case the task needs to be scheduled.
        /// Otherwise, the method returns false.</returns>
        /// 
        internal bool Initialize(EngineController controller, HomeWorkspaceModel workspace)
        {
            if (controller == null || (controller.LiveRunnerCore == null))
                return false;

            engineController = controller;
            traceData = workspace.PreloadedTraceData;

            TargetedWorkspace = workspace;
            workspace.PreloadedTraceData = null;
            return ((traceData != null) && traceData.Any());
        }
 /// <summary>
 /// This method is called by codes that intent to start a graph update.
 /// This method is called on the main thread where node collection in a 
 /// WorkspaceModel can be safely accessed.
 /// </summary>
 /// <param name="controller">Reference to an instance of EngineController 
 /// to assist in generating GraphSyncData object for the given set of nodes.
 /// </param>
 /// <param name="workspace">Reference to the WorkspaceModel from which a 
 /// set of updated nodes is computed. The EngineController generates the 
 /// resulting GraphSyncData from this list of updated nodes.</param>
 /// <returns>Returns the list of node id's that will be executed in the next run
 /// for execution).</returns>
 internal List<Guid> Initialize(EngineController controller, WorkspaceModel workspace)
 {
     try
     {
         engineController = controller;
         TargetedWorkspace = workspace;                
         modifiedNodes = ComputeModifiedNodes(workspace);                
         previewGraphData = engineController.PreviewGraphSyncData(modifiedNodes,verboseLogging);
         return previewGraphData;
     }
     catch (Exception e)
     {             
         return null;
     }
 }
        /// <summary>
        /// Create hight lighting rule for method.
        /// </summary>
        /// <returns></returns>
        public static HighlightingRule CreateMethodHighlightRule(EngineController engineController)
        {
            Color color = (Color)ColorConverter.ConvertFromString("#417693");
            var methodHighlightRule = new HighlightingRule
            {
                Color = new HighlightingColor()
                {
                    Foreground = new CodeHighlightingRuleFactory.CustomizedBrush(color)
                }
            };

            var wordList = engineController.CodeCompletionServices.GetGlobals();
            String regex = String.Format(@"\b({0})({0})?\b", String.Join("|", wordList));
            methodHighlightRule.Regex = new Regex(regex);

            return methodHighlightRule;
        }
        /// <summary>
        /// Create hight lighting rule for class.
        /// </summary>
        /// <param name="engineController"></param>
        /// <returns></returns>
        public static HighlightingRule CreateClassHighlightRule(EngineController engineController)
        {
            Color color = (Color)ColorConverter.ConvertFromString("#2E998F");
            var classHighlightRule = new HighlightingRule
            {
                Color = new HighlightingColor()
                {
                    Foreground = new CodeHighlightingRuleFactory.CustomizedBrush(color)
                }
            };

            var wordList = engineController.CodeCompletionServices.GetClasses();
            String regex = String.Format(@"\b({0})\b", String.Join("|", wordList));
            classHighlightRule.Regex = new Regex(regex);

            return classHighlightRule;
        }
        public static List<IGraphicItem> GeneratedGraphicItems(this NodeModel node, EngineController engineController)
        {
            var ids = node.GetAllOutportAstIdentifiers();

            var results = new List<IGraphicItem>();

            foreach (var id in ids)
            {
                var mirror = engineController.GetMirror(id);
                if (mirror == null) continue;

                var mirrorData = mirror.GetData();
                if (mirrorData == null) continue;

                GetGraphicItemsFromMirrorData(mirrorData, results);
            }

            return results;
        }
        /// <summary>
        /// Call this method to intialize a CompileCustomNodeAsyncTask with an 
        /// EngineController and an GraphSyncData that is required to compile the 
        /// associated custom node.
        /// </summary>
        /// <param name="initParams">Input parameters required for custom node 
        /// graph updates.</param>
        /// <returns>Returns true if GraphSyncData is not empty and that the 
        /// CompileCustomNodeAsyncTask should be scheduled for execution. Returns
        /// false otherwise.</returns>
        /// 
        internal bool Initialize(CompileCustomNodeParams initParams)
        {
            if (initParams == null)
                throw new ArgumentNullException("initParams");

            engineController = initParams.EngineController;
            graphSyncData = initParams.SyncData;

            if (engineController == null)
                throw new ArgumentNullException("engineController");
            if (graphSyncData == null)
                throw new ArgumentNullException("graphSyncData");

            var added = graphSyncData.AddedSubtrees;
            var deleted = graphSyncData.DeletedSubtrees;
            var modified = graphSyncData.ModifiedSubtrees;

            // Returns true if there is any actual data.
            return ((added != null && added.Count > 0) ||
                    (modified != null && modified.Count > 0) ||
                    (deleted != null && deleted.Count > 0));
        }
 internal static ILiveRunner CreateLiveRunner(EngineController controller, string geometryFactoryFileName)
 {
     var configuration = new LiveRunner.Configuration();
     configuration.PassThroughConfiguration.Add(Autodesk.DesignScript.Interfaces.ConfigurationKeys.GeometryFactory, geometryFactoryFileName);
     return new LiveRunner(configuration);
 }
Beispiel #12
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();

            ExecuteAndWait();

            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;
        }
Beispiel #13
0
 public override bool RequestVisualUpdateAsync(
     IScheduler scheduler, EngineController engine, IRenderPackageFactory factory, bool forceUpdate = false)
 {
     // No visualization update is required for this node type.
     return false;
 }
Beispiel #14
0
        /// <summary>
        /// Call this method to reset the virtual machine, avoiding a race 
        /// condition by using a thread join inside the vm executive.
        /// TODO(Luke): Push this into a resync call with the engine controller
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="markNodesAsDirty">Set this parameter to true to force 
        ///     reset of the execution substrait. Note that setting this parameter 
        ///     to true will have a negative performance impact.</param>
        public void ResetEngine(EngineController controller, bool markNodesAsDirty = false)
        {
            if (EngineController != null)
            {
                EngineController.MessageLogged -= Log;
                EngineController.LibraryServices.LibraryLoaded -= LibraryLoaded;
            }

            EngineController = controller;
            controller.MessageLogged += Log;
            controller.LibraryServices.LibraryLoaded += LibraryLoaded;
            
            if (markNodesAsDirty)
            {
                // Mark all nodes as dirty so that AST for the whole graph will be
                // regenerated.
                MarkNodesAsModifiedAndRequestRun(Nodes); 
            }

            if (RunSettings.RunType == RunType.Automatic)
                Run();
        }
Beispiel #15
0
        public HomeWorkspaceModel(
            EngineController engine, 
            DynamoScheduler scheduler, 
            NodeFactory factory,
            IEnumerable<KeyValuePair<Guid, List<string>>> traceData, 
            IEnumerable<NodeModel> e, 
            IEnumerable<NoteModel> n, 
            IEnumerable<AnnotationModel> a,
            IEnumerable<PresetModel> presets,
            ElementResolver resolver,
            WorkspaceInfo info, 
            bool verboseLogging,
            bool isTestMode)
            : base(e, n,a, info, factory,presets, resolver)
        {
            EvaluationCount = 0;

            // This protects the user from a file that might have crashed during
            // its last run.  As a side effect, this also causes all files set to
            // run auto but lacking the HasRunWithoutCrash flag to run manually.
            if (info.RunType == RunType.Automatic && !info.HasRunWithoutCrash)
            {
                info.RunType = RunType.Manual;
            }

            RunSettings = new RunSettings(info.RunType, info.RunPeriod);

            PreloadedTraceData = traceData;

            this.scheduler = scheduler;
            this.verboseLogging = verboseLogging;
            IsTestMode = isTestMode;
            EngineController = engine;

            // The first time the preloaded trace data is set, we cache
            // the data as historical. This will be used after the initial
            // run of this workspace, when the PreloadedTraceData has been
            // nulled, to check for node deletions and reconcile the trace data.
            // We do a deep copy of this data because the PreloadedTraceData is
            // later set to null before the graph update.
            var copiedData = new List<KeyValuePair<Guid, List<string>>>();
            foreach (var kvp in PreloadedTraceData)
            {
                var strings = kvp.Value.Select(string.Copy).ToList();
                copiedData.Add(new KeyValuePair<Guid, List<string>>(kvp.Key, strings));
            }
            historicalTraceData = copiedData;

        }
Beispiel #16
0
 public HomeWorkspaceModel(EngineController engine, DynamoScheduler scheduler, 
     NodeFactory factory, bool verboseLogging, bool isTestMode, string fileName="")
     : this(
         engine,
         scheduler,
         factory,
         Enumerable.Empty<KeyValuePair<Guid, List<string>>>(),
         Enumerable.Empty<NodeModel>(),
         Enumerable.Empty<NoteModel>(),
         Enumerable.Empty<AnnotationModel>(),
         Enumerable.Empty<PresetModel>(),
         new ElementResolver(),
         new WorkspaceInfo(){FileName = fileName, Name = "Home"},
         verboseLogging, 
         isTestMode) { }
Beispiel #17
0
 public override void RequestVisualUpdateAsync(
     IScheduler scheduler, EngineController engine, IRenderPackageFactory factory, bool forceUpdate = false)
 {
     //Do nothing
 }
 public HomeWorkspaceModel(Guid guid, EngineController engine,
     DynamoScheduler scheduler,
     NodeFactory factory,
     IEnumerable<KeyValuePair<Guid, List<CallSite.RawTraceData>>> traceData,
     IEnumerable<NodeModel> nodes,
     IEnumerable<NoteModel> notes,
     IEnumerable<AnnotationModel> annotations,
     IEnumerable<PresetModel> presets,
     ElementResolver resolver,
     WorkspaceInfo info,
     bool verboseLogging,
     bool isTestMode):this(engine, scheduler, factory, traceData, nodes, notes, 
         annotations, presets, resolver, info, verboseLogging, isTestMode)
 { Guid = guid; }
 public WorkspaceConverter(EngineController engine, 
     DynamoScheduler scheduler, NodeFactory factory, bool isTestMode, bool verboseLogging)
 {
     this.scheduler = scheduler;
     this.engine = engine;
     this.factory = factory;
     this.isTestMode = isTestMode;
     this.verboseLogging = verboseLogging;
 }
 public LiveRunnerServices(EngineController controller, string geometryFactoryFileName)
 {
     liveRunner = LiveRunnerFactory.CreateLiveRunner(controller, geometryFactoryFileName);
 }
 public LiveRunnerServices(EngineController controller, string geometryFactoryFileName)
 {
     liveRunner = LiveRunnerFactory.CreateLiveRunner(controller, geometryFactoryFileName);
 }
Beispiel #22
0
        internal void ConvertNodesToCodeInternal(EngineController engineController, INamingProvider namingProvider)
        {
            var selectedNodes = DynamoSelection.Instance
                                               .Selection
                                               .OfType<NodeModel>()
                                               .Where(n => n.IsConvertible);
            if (!selectedNodes.Any())
                return;

            var cliques = NodeToCodeCompiler.GetCliques(selectedNodes).Where(c => !(c.Count == 1 && c.First() is CodeBlockNodeModel));
            var codeBlockNodes = new List<CodeBlockNodeModel>();

            //UndoRedo Action Group----------------------------------------------
            NodeToCodeUndoHelper undoHelper = new NodeToCodeUndoHelper();

            // using (UndoRecorder.BeginActionGroup())
            {
                foreach (var nodeList in cliques)
                {
                    //Create two dictionarys to store the details of the external connections that have to 
                    //be recreated after the conversion
                    var externalInputConnections = new Dictionary<ConnectorModel, string>();
                    var externalOutputConnections = new Dictionary<ConnectorModel, string>();

                    //Also collect the average X and Y co-ordinates of the different nodes
                    int nodeCount = nodeList.Count;

                    var nodeToCodeResult = engineController.ConvertNodesToCode(this.nodes, nodeList, namingProvider);

                    #region Step I. Delete all nodes and their connections

                    double totalX = 0, totalY = 0;

                    foreach (var node in nodeList)
                    {
                        #region Step I.A. Delete the connections for the node

                        foreach (var connector in node.AllConnectors.ToList())
                        {
                            if (!IsInternalNodeToCodeConnection(nodeList, connector))
                            {
                                //If the connector is an external connector, the save its details
                                //for recreation later
                                var startNode = connector.Start.Owner;
                                int index = startNode.OutPorts.IndexOf(connector.Start);
                                //We use the varibleName as the connection between the port of the old Node
                                //to the port of the new node.
                                var variableName = startNode.GetAstIdentifierForOutputIndex(index).Value;

                                //Store the data in the corresponding dictionary
                                if (startNode == node)
                                {
                                    if (nodeToCodeResult.OutputMap.ContainsKey(variableName))
                                        variableName = nodeToCodeResult.OutputMap[variableName];
                                    externalOutputConnections.Add(connector, variableName);
                                }
                                else
                                {
                                    if (nodeToCodeResult.InputMap.ContainsKey(variableName))
                                        variableName = nodeToCodeResult.InputMap[variableName];
                                    externalInputConnections.Add(connector, variableName);
                                }
                            }

                            //Delete the connector
                            undoHelper.RecordDeletion(connector);
                            connector.Delete();
                        }
                        #endregion

                        #region Step I.B. Delete the node
                        totalX += node.X;
                        totalY += node.Y;
                        undoHelper.RecordDeletion(node);
                        RemoveNode(node);
                        #endregion
                    }
                    #endregion

                    #region Step II. Create the new code block node
                    var outputVariables = externalOutputConnections.Values;
                    var newResult = NodeToCodeCompiler.ConstantPropagationForTemp(nodeToCodeResult, outputVariables);

                    // Rewrite the AST using the shortest unique name in case of namespace conflicts
                    NodeToCodeCompiler.ReplaceWithShortestQualifiedName(
                        engineController.LibraryServices.LibraryManagementCore.ClassTable, newResult.AstNodes, ElementResolver);
                    var codegen = new ProtoCore.CodeGenDS(newResult.AstNodes);
                    var code = codegen.GenerateCode();

                    var codeBlockNode = new CodeBlockNodeModel(
                        code,
                        System.Guid.NewGuid(), 
                        totalX / nodeCount,
                        totalY / nodeCount, engineController.LibraryServices, ElementResolver);
                    undoHelper.RecordCreation(codeBlockNode);
                   
                    AddAndRegisterNode(codeBlockNode, false);
                    codeBlockNodes.Add(codeBlockNode);
                    #endregion

                    #region Step III. Recreate the necessary connections
                    var newInputConnectors = ReConnectInputConnections(externalInputConnections, codeBlockNode);
                    foreach (var connector in newInputConnectors)
                    {
                        undoHelper.RecordCreation(connector);
                    }

                    var newOutputConnectors = ReConnectOutputConnections(externalOutputConnections, codeBlockNode);
                    foreach (var connector in newOutputConnectors)
                    {
                        undoHelper.RecordCreation(connector);
                    }
                    #endregion
                }
            }

            undoHelper.ApplyActions(UndoRecorder);

            DynamoSelection.Instance.ClearSelection();
            DynamoSelection.Instance.Selection.AddRange(codeBlockNodes);

            RequestRun();
        }
        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(0);

            IEnumerable<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(0);

            IEnumerable<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;
        }
        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;
        }
Beispiel #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;
        }
        internal bool Initialize(UpdateRenderPackageParams initParams)
        {
            if (initParams == null)
                throw new ArgumentNullException("initParams");
            if (initParams.Node == null)
                throw new ArgumentNullException("initParams.Node");
            if (initParams.EngineController == null)
                throw new ArgumentNullException("initParams.EngineController");
            if (initParams.DrawableIds == null)
                throw new ArgumentNullException("initParams.DrawableIds");

            var nodeModel = initParams.Node;
            if (!nodeModel.WasInvolvedInExecution && !initParams.ForceUpdate)
                return false; // Not has not been updated at all.

            // If a node is in either of the following states, then it will not 
            // produce any geometric output. Bail after clearing the render packages.
            if (nodeModel.IsInErrorState || !nodeModel.IsVisible)
                return false;

            // Without AstIdentifierForPreview, a node cannot have MirrorData.
            if (string.IsNullOrEmpty(nodeModel.AstIdentifierForPreview.Value))
                return false;

            drawableIds = initParams.DrawableIds;
            if (!drawableIds.Any())
                return false; // Nothing to be drawn.

            displayLabels = nodeModel.DisplayLabels;
            isNodeSelected = nodeModel.IsSelected;
            factory = initParams.RenderPackageFactory;
            engineController = initParams.EngineController;
            previewIdentifierName = initParams.PreviewIdentifierName;

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

            int workspaceIndex = DynamoViewModel.CurrentWorkspaceIndex;

            var firstNodeConnectors = node.AllConnectors.ToList();

            var valueMap = new Dictionary<Guid, String>();
            foreach (ConnectorModel connector in firstNodeConnectors)
            {
                if (connector.End.Owner.GUID != node.GUID)
                {
                    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();
                }
            }

            string customNodeFilePath = string.Empty;

            var function = node as Function;
            CustomNodeInfo info = null;
            if (function != null)
            {
                var id = function.Definition.FunctionId;
                if (DynamoViewModel.Model.CustomNodeManager.TryGetNodeInfo(id, out info))
                {
                    customNodeFilePath = info.Path;
                }
            }

            var workspaces = DynamoViewModel.Model.Workspaces;

            if (File.Exists(customNodeFilePath))
            {
                DynamoViewModel.UIDispatcher.Invoke(new Action(() =>
                {
                    DynamoModel.OpenFileCommand openFile =
                        new DynamoModel.OpenFileCommand(customNodeFilePath);

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

                var nodesInCustomNodeBeforeMutation =
                    workspaces.FirstOrDefault((t) => (t.Name == info.Name)).Nodes.ToList();

                var customNodeStructureBeforeMutation = 
                    GetDictionaryOfConnectedNodes(nodesInCustomNodeBeforeMutation);

                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();

                ExecuteAndWait();

                DynamoViewModel.UIDispatcher.Invoke(new Action(() =>
                {
                    DynamoModel.SwitchTabCommand switchCmd =
                        new DynamoModel.SwitchTabCommand(workspaceIndex);

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

                var nodesInCustomNodeAfterMutation =
                    workspaces.FirstOrDefault((t) => (t.Name == info.Name)).Nodes.ToList();

                var customNodeStructureAfterMutation = 
                    GetDictionaryOfConnectedNodes(nodesInCustomNodeAfterMutation);

                writer.WriteLine("### - Beginning test of CustomNode structure");
                if (customNodeStructureBeforeMutation.Count == customNodeStructureAfterMutation.Count)
                {
                    foreach (var item in customNodeStructureAfterMutation)
                    {
                        if (item.Value != customNodeStructureBeforeMutation[item.Key])
                        {
                            writer.WriteLine("!!!!!!!!!!! - test of CustomNode structure is failed");
                            writer.Flush();
                            return pass;
                        }
                    }
                }
                else
                {
                    writer.WriteLine("!!!!!!!!!!! - test of CustomNode structure is failed");
                    writer.Flush();
                    return pass;
                }

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

                        if (nodeAfterUndo == null)
                        {
                            writer.WriteLine("!!!!!!!!!!! - test of CustomNode is failed");
                            writer.Flush();
                            return pass;
                        }

                        var firstNodeConnectorsAfterUndo = nodeAfterUndo.AllConnectors.ToList();

                        foreach (ConnectorModel connector in firstNodeConnectorsAfterUndo)
                        {
                            if (connector.End.Owner.GUID != node.GUID)
                            {
                                Object data = connector.Start.Owner.GetValue(0, engine).Data;
                                String nodeVal = data != null ? data.ToString() : "null";

                                if (valueMap[connector.Start.Owner.GUID] != nodeVal)
                                {
                                    writer.WriteLine("!!!!!!!!!!! - test of CustomNode is failed");
                                    writer.WriteLine(node.GUID);

                                    writer.WriteLine("Was: " + nodeVal);
                                    writer.WriteLine("Should have been: " + 
                                        valueMap[connector.End.Owner.GUID]);
                                    writer.Flush();
                                    return pass;
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                        writer.WriteLine("!!!!!!!!!!! - test of CustomNode is failed");
                        writer.Flush();
                        return pass;
                    }
                }
                var workspacesOfCustomNodes = DynamoViewModel.Workspaces.Where((t) =>
                    {
                        return (t.Model is CustomNodeWorkspaceModel);
                    }).ToList();

                if (workspacesOfCustomNodes != null)
                {
                    foreach (var item in workspacesOfCustomNodes)
                    {
                        DynamoViewModel.UIDispatcher.Invoke(new Action(() =>
                        {
                            DynamoModel.SwitchTabCommand swithCommand =
                                new DynamoModel.SwitchTabCommand(workspaceIndex);

                            DynamoViewModel.ExecuteCommand(swithCommand);

                            DynamoViewModel.Workspaces.Remove(item);
                        }));
                    }
                }

                writer.WriteLine("### - test of CustomNode complete");
                writer.Flush();
            }
            return pass = true;
        }
Beispiel #28
0
 public abstract bool RunTest(NodeModel node, EngineController engine, StreamWriter writer);
Beispiel #29
0
        public override bool RunTest(NodeModel node, EngineController engine, StreamWriter writer)
        {
            const bool pass = false;

            var nodes = DynamoViewModel.Model.CurrentWorkspace.Nodes;
            if (nodes.Count() == 0)
                return pass;

            int nodesCountBeforeCopying = nodes.Count();

            int numberOfUndosNeeded = this.Mutate(node);
            Thread.Sleep(10);

            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(0);
            }
            writer.WriteLine("### - undo complete");
            writer.Flush();

            ExecuteAndWait();

            writer.WriteLine("### - Beginning test of CopyNode");
            if (node.OutPorts.Count > 0)
            {
                try
                {
                    int nodesCountAfterCopying = DynamoViewModel.Model.CurrentWorkspace.Nodes.Count();

                    if (nodesCountBeforeCopying != nodesCountAfterCopying)
                    {
                        writer.WriteLine("!!!!!!!!!!! - test of CopyNode is failed");
                        writer.WriteLine(node.GUID);

                        writer.WriteLine("Was: " + nodesCountAfterCopying);
                        writer.WriteLine("Should have been: " + nodesCountBeforeCopying);
                        writer.Flush();
                        return pass;
                    }
                    else
                    {
                        writer.WriteLine("### - test of CopyNode is passed");
                        writer.Flush();
                    }

                }
                catch (Exception)
                {
                    writer.WriteLine("!!!!!!!!!!! - test of CopyNode is failed");
                    writer.Flush();
                    return pass;
                }
            }
            writer.WriteLine("### - test of CopyNode complete");
            writer.Flush();

            return true;
        }
Beispiel #30
0
        protected void ResetEngineInternal()
        {
            if (EngineController != null)
            {
                EngineController.TraceReconcliationComplete -= EngineController_TraceReconcliationComplete;
                EngineController.MessageLogged -= LogMessage;
                EngineController.Dispose();
                EngineController = null;
            }

            EngineController = new EngineController(
                LibraryServices,
                geometryFactoryPath,
                DebugSettings.VerboseLogging);

            EngineController.MessageLogged += LogMessage;
            EngineController.TraceReconcliationComplete += EngineController_TraceReconcliationComplete;

            foreach (var def in CustomNodeManager.LoadedDefinitions)
                RegisterCustomNodeDefinitionWithEngine(def);
        }
Beispiel #31
0
        public ColorRange1D ComputeColorRange(EngineController engine)
        {
            List<Color> colors;
            List<double> parameters;

            // If there are colors supplied
            if (HasConnectedInput(0))
            {
                var colorsNode = InPorts[0].Connectors[0].Start.Owner;
                var colorsIndex = InPorts[0].Connectors[0].Start.Index;
                var startId = colorsNode.GetAstIdentifierForOutputIndex(colorsIndex).Name;
                var colorsMirror = engine.GetMirror(startId);
                colors = GetColorsFromMirrorData(colorsMirror);
            }
            else
            {
                colors = new List<Color>();
                colors.AddRange(DefaultColorRanges.Analysis);
            }

            // If there are indices supplied
            if (HasConnectedInput(1))
            {
                var valuesNode = InPorts[1].Connectors[0].Start.Owner;
                var valuesIndex = InPorts[1].Connectors[0].Start.Index;
                var endId = valuesNode.GetAstIdentifierForOutputIndex(valuesIndex).Name;
                var valuesMirror = engine.GetMirror(endId);
                parameters = GetValuesFromMirrorData(valuesMirror);
            }
            else
            {
                parameters = CreateParametersForColors(colors);
            }

            return ColorRange1D.ByColorsAndParameters(colors, parameters);
        }