Ejemplo n.º 1
0
        private static void startDynamo()
        {
            try
            {
                ExecutingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                string tempPath = Path.GetTempPath();

                TempFolder = Path.Combine(tempPath, "dynamoTmp");

                if (!Directory.Exists(TempFolder))
                {
                    Directory.CreateDirectory(TempFolder);
                }
                else
                {
                    smptyTempFolder();
                }

                DynamoLogger.Instance.StartLogging();

                //create a new instance of the ViewModel
                controller         = new DynamoController(new FSchemeInterop.ExecutionEnvironment(), typeof(DynamoViewModel), Context.NONE);
                controller.Testing = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }
Ejemplo n.º 2
0
        private void StartDynamo()
        {
            try
            {
                SIUnit.HostApplicationInternalAreaUnit   = DynamoAreaUnit.SquareFoot;
                SIUnit.HostApplicationInternalLengthUnit = DynamoLengthUnit.DecimalFoot;
                SIUnit.HostApplicationInternalVolumeUnit = DynamoVolumeUnit.CubicFoot;

                var logger        = new DynamoLogger();
                var updateManager = new UpdateManager.UpdateManager(logger);

                //create a new instance of the ViewModel
                Controller = new DynamoController(Context.NONE, updateManager, logger,
                                                  new DefaultWatchHandler(), new PreferenceSettings());
                DynamoController.IsTestMode     = true;
                Controller.DynamoViewModel      = new DynamoViewModel(Controller, null);
                Controller.VisualizationManager = new VisualizationManager();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }

            //create the transaction manager object
            TransactionManager.SetupManager(new AutomaticTransactionStrategy());

            //tests do not run from idle thread
            TransactionManager.Instance.DoAssertInIdleThread = false;
        }
Ejemplo n.º 3
0
        public void Start()
        {
            AppDomain.CurrentDomain.AssemblyResolve += AssemblyHelper.CurrentDomain_AssemblyResolve;

            Controller = DynamoController.MakeSandbox();

            //create the view
            Ui                      = new DynamoView();
            Ui.DataContext          = Controller.DynamoViewModel;
            Vm                      = Controller.DynamoViewModel;
            Model                   = Controller.DynamoModel;
            Controller.UIDispatcher = Ui.Dispatcher;
            Ui.Show();

            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

            string tempPath = Path.GetTempPath();

            TempFolder = Path.Combine(tempPath, "dynamoTmp");

            if (!Directory.Exists(TempFolder))
            {
                Directory.CreateDirectory(TempFolder);
            }
            else
            {
                EmptyTempFolder();
            }
        }
Ejemplo n.º 4
0
 protected AbstractMutator(Random rand)
 {
     this.rand            = rand;
     this.controller      = dynSettings.Controller;
     this.dynamoViewModel = controller.DynamoViewModel;
     this.dynamoModel     = controller.DynamoModel;
 }
Ejemplo n.º 5
0
        private void RestartTestSetup()
        {
            // Shutdown Dynamo and restart it
            Ui.Close();
            if (Controller != null)
            {
                Controller.ShutDown(false);
                Controller = null;
            }

            // Setup Temp PreferenceSetting Location for testing
            PreferenceSettings.DYNAMO_TEST_PATH = Path.Combine(TempFolder, "UserPreferenceTest.xml");

            Controller = DynamoController.MakeSandbox();
            DynamoController.IsTestMode = true;

            //create the view
            Ui                      = new DynamoView();
            Ui.DataContext          = Controller.DynamoViewModel;
            Vm                      = Controller.DynamoViewModel;
            Controller.UIDispatcher = Ui.Dispatcher;
            Ui.Show();

            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
        }
Ejemplo n.º 6
0
        private void StartDynamo()
        {
            try
            {
                SIUnit.HostApplicationInternalAreaUnit = DynamoAreaUnit.SquareFoot;
                SIUnit.HostApplicationInternalLengthUnit = DynamoLengthUnit.DecimalFoot;
                SIUnit.HostApplicationInternalVolumeUnit = DynamoVolumeUnit.CubicFoot;

                var logger = new DynamoLogger();
                var updateManager = new UpdateManager.UpdateManager(logger);

                //create a new instance of the ViewModel
                Controller = new DynamoController(Context.NONE, updateManager, logger, 
                    new DefaultWatchHandler(), new PreferenceSettings());
                DynamoController.IsTestMode = true;
                Controller.DynamoViewModel = new DynamoViewModel(Controller, null);
                Controller.VisualizationManager = new VisualizationManager();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }

            //create the transaction manager object
            TransactionManager.SetupManager(new AutomaticTransactionStrategy());

            //tests do not run from idle thread
            TransactionManager.Instance.DoAssertInIdleThread = false;
        }
Ejemplo n.º 7
0
        private void StartDynamo()
        {
            try
            {
                var updater = new RevitServicesUpdater(DynamoRevitApp.ControlledApplication, DynamoRevitApp.Updaters);
                updater.ElementAddedForID += ElementMappingCache.GetInstance().WatcherMethodForAdd;
                updater.ElementsDeleted   += ElementMappingCache.GetInstance().WatcherMethodForDelete;

                SIUnit.HostApplicationInternalAreaUnit   = DynamoAreaUnit.SquareFoot;
                SIUnit.HostApplicationInternalLengthUnit = DynamoLengthUnit.DecimalFoot;
                SIUnit.HostApplicationInternalVolumeUnit = DynamoVolumeUnit.CubicFoot;

                var logger = new DynamoLogger();
                dynSettings.DynamoLogger = logger;
                var updateManager = new UpdateManager.UpdateManager(logger);

                Controller = DynamoRevit.CreateDynamoRevitControllerAndViewModel(updater, logger, Context.NONE);
                DynamoController.IsTestMode = true;

                // create the transaction manager object
                TransactionManager.SetupManager(new AutomaticTransactionStrategy());

                // Because the test framework does not work in the idle thread.
                // We need to trick Dynamo into believing that it's in the idle
                // thread already.
                IdlePromise.InIdleThread = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }
Ejemplo n.º 8
0
        private void Init(IUpdateManager updateManager)
        {
            AppDomain.CurrentDomain.AssemblyResolve += AssemblyHelper.CurrentDomain_AssemblyResolve;

            Controller = new DynamoController("None", updateManager,
                                              new DefaultWatchHandler(), new PreferenceSettings());
            DynamoController.IsTestMode     = true;
            Controller.DynamoViewModel      = new DynamoViewModel(Controller, null);
            Controller.VisualizationManager = new VisualizationManager();

            //create the view
            Ui = new DynamoView {
                DataContext = Controller.DynamoViewModel
            };
            Vm = Controller.DynamoViewModel;
            Controller.UIDispatcher = Ui.Dispatcher;
            Ui.Show();

            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

            string tempPath = Path.GetTempPath();

            TempFolder = Path.Combine(tempPath, "dynamoTmp");

            if (!Directory.Exists(TempFolder))
            {
                Directory.CreateDirectory(TempFolder);
            }
            else
            {
                DynamoTestUI.EmptyTempFolder(TempFolder);
            }
        }
Ejemplo n.º 9
0
 protected AbstractMutator(Random rand)
 {
     this.Rand = rand;
     this.Controller = dynSettings.Controller;
     this.DynamoViewModel = Controller.DynamoViewModel;
     this.DynamoModel = Controller.DynamoModel;
 }
Ejemplo n.º 10
0
        public virtual void Start()
        {
            AppDomain.CurrentDomain.AssemblyResolve += AssemblyHelper.ResolveAssembly;

            string tempPath = Path.GetTempPath();

            TempFolder = Path.Combine(tempPath, "dynamoTmp");

            if (!Directory.Exists(TempFolder))
            {
                Directory.CreateDirectory(TempFolder);
            }
            else
            {
                EmptyTempFolder(TempFolder);
            }

            // Setup Temp PreferenceSetting Location for testing
            PreferenceSettings.DYNAMO_TEST_PATH = Path.Combine(TempFolder, "UserPreferenceTest.xml");

            Controller = DynamoController.MakeSandbox();
            DynamoController.IsTestMode = true;

            //create the view
            Ui                      = new DynamoView();
            Ui.DataContext          = Controller.DynamoViewModel;
            Vm                      = Controller.DynamoViewModel;
            Model                   = Controller.DynamoModel;
            Controller.UIDispatcher = Ui.Dispatcher;
            Ui.Show();

            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
        }
Ejemplo n.º 11
0
        public DynamoViewModel(DynamoController controller)
        {
            //MVVM: Instantiate the model
            _model = new DynamoModel();
            _model.Workspaces.CollectionChanged += Workspaces_CollectionChanged;

            _model.PropertyChanged += _model_PropertyChanged;

            dynSettings.Controller.DynamoModel = _model;

            _model.AddHomeWorkspace();
            _model.CurrentSpace = _model.HomeSpace;

            Controller = controller;
            sw = new StringWriter();
            ConnectorType = ConnectorType.BEZIER;

            #region Initialize Commands
            GoToWikiCommand = new DelegateCommand(GoToWiki, CanGoToWiki);
            ReportABugCommand = new DelegateCommand(ReportABug, CanReportABug);
            GoToSourceCodeCommand = new DelegateCommand(GoToSourceCode,  CanGoToSourceCode);
            CleanupCommand = new DelegateCommand(Cleanup, CanCleanup);
            ExitCommand = new DelegateCommand<object>(Exit, CanExit);
            NewHomeWorkspaceCommand = new DelegateCommand(MakeNewHomeWorkspace, CanMakeNewHomeWorkspace);
            ShowSaveImageDialogAndSaveResultCommand = new DelegateCommand(ShowSaveImageDialogAndSaveResult, CanShowSaveImageDialogAndSaveResult);
            ShowOpenDialogAndOpenResultCommand = new DelegateCommand(ShowOpenDialogAndOpenResult, CanShowOpenDialogAndOpenResultCommand);
            ShowSaveDialogIfNeededAndSaveResultCommand = new DelegateCommand(ShowSaveDialogIfNeededAndSaveResult, CanShowSaveDialogIfNeededAndSaveResultCommand);
            ShowSaveDialogAndSaveResultCommand = new DelegateCommand(ShowSaveDialogAndSaveResult, CanShowSaveDialogAndSaveResultCommand);
            ShowNewFunctionDialogCommand = new DelegateCommand(ShowNewFunctionDialog, CanShowNewFunctionDialogCommand);
            SaveCommand = new DelegateCommand(Save, CanSave);
            OpenCommand = new DelegateCommand<object>(Open, CanOpen);
            SaveAsCommand = new DelegateCommand<object>(SaveAs, CanSaveAs);
            ClearCommand = new DelegateCommand(Clear, CanClear);
            HomeCommand = new DelegateCommand(Home, CanGoHome);
            LayoutAllCommand = new DelegateCommand(LayoutAll, CanLayoutAll);
            CopyCommand = new DelegateCommand<object>(Copy, CanCopy);
            PasteCommand = new DelegateCommand<object>(Paste, CanPaste);
            ToggleConsoleShowingCommand = new DelegateCommand(ToggleConsoleShowing, CanToggleConsoleShowing);
            ToggleFullscreenWatchShowingCommand = new DelegateCommand(ToggleFullscreenWatchShowing, CanToggleFullscreenWatchShowing);
            ToggleCanNavigateBackgroundCommand = new DelegateCommand(ToggleCanNavigateBackground, CanToggleCanNavigateBackground);
            CancelRunCommand = new DelegateCommand(CancelRun, CanCancelRun);
            SaveImageCommand = new DelegateCommand<object>(SaveImage, CanSaveImage);
            ClearLogCommand = new DelegateCommand(ClearLog, CanClearLog);
            RunExpressionCommand = new DelegateCommand<object>(RunExpression,CanRunExpression);
            ShowPackageManagerCommand = new DelegateCommand(ShowPackageManager,CanShowPackageManager);
            GoToWorkspaceCommand = new DelegateCommand<object>(GoToWorkspace, CanGoToWorkspace);
            DisplayFunctionCommand = new DelegateCommand<object>(DisplayFunction, CanDisplayFunction);
            SetConnectorTypeCommand = new DelegateCommand<object>(SetConnectorType, CanSetConnectorType);
            CreateNodeCommand = new DelegateCommand<object>(CreateNode, CanCreateNode);
            CreateConnectionCommand = new DelegateCommand<object>(CreateConnection, CanCreateConnection);
            AddNoteCommand = new DelegateCommand<object>(AddNote, CanAddNote);
            DeleteCommand = new DelegateCommand<object>(Delete, CanDelete);
            SelectNeighborsCommand = new DelegateCommand<object>(SelectNeighbors, CanSelectNeighbors);
            AddToSelectionCommand = new DelegateCommand<object>(AddToSelection, CanAddToSelection);
            PostUIActivationCommand = new DelegateCommand(PostUIActivation, CanDoPostUIActivation);
            RefactorCustomNodeCommand = new DelegateCommand(RefactorCustomNode, CanRefactorCustomNode);
            ShowHideConnectorsCommand = new DelegateCommand(ShowConnectors, CanShowConnectors);
            #endregion
        }
Ejemplo n.º 12
0
 /// <summary>
 /// Enables starting Dynamo with a mock IUpdateManager
 /// </summary>
 /// <param name="updateManager"></param>
 /// <param name="watchHandler"></param>
 /// <param name="preferences"></param>
 /// <param name="visualizationManager"></param>
 protected void StartDynamo(IUpdateManager updateManager, IWatchHandler watchHandler, IPreferences preferences, IVisualizationManager visualizationManager)
 {
     //create a new instance of the ViewModel
     Controller = new DynamoController(Context.NONE, updateManager, watchHandler, preferences);
     Controller.DynamoViewModel      = new DynamoViewModel(Controller, null);
     DynamoController.IsTestMode     = true;
     Controller.VisualizationManager = new VisualizationManager();
 }
Ejemplo n.º 13
0
 private void StartDynamo()
 {
     //create a new instance of the ViewModel
     Controller = new DynamoController(new ExecutionEnvironment(), typeof (DynamoViewModel), Context.NONE)
     {
         Testing = true
     };
 }
Ejemplo n.º 14
0
 protected void StartDynamo()
 {
     //create a new instance of the ViewModel
     Controller = new DynamoController(new ExecutionEnvironment(), typeof (DynamoViewModel), Context.NONE, new UpdateManager.UpdateManager(), new UnitsManager())
     {
         Testing = true
     };
 }
Ejemplo n.º 15
0
 /// <summary>
 /// Enables starting Dynamo with a mock IUpdateManager
 /// </summary>
 /// <param name="updateManager"></param>
 /// <param name="watchHandler"></param>
 /// <param name="preferences"></param>
 /// <param name="visualizationManager"></param>
 protected void StartDynamo(IUpdateManager updateManager, ILogger logger, IWatchHandler watchHandler, IPreferences preferences, IVisualizationManager visualizationManager)
 {
     //create a new instance of the ViewModel
     Controller = new DynamoController(Context.NONE, updateManager, logger, watchHandler, preferences);
     Controller.DynamoViewModel = new DynamoViewModel(Controller, null);
     DynamoController.IsTestMode = true;
     Controller.VisualizationManager = new VisualizationManager();
 }
Ejemplo n.º 16
0
        /// <summary>
        ///     Get a dynFunction from a guid, also stores type internally info for future instantiation.
        ///     And add the compiled node to the enviro
        ///     As a side effect, any of its dependent nodes are also initialized.
        /// </summary>
        /// <param name="environment">The environment from which to get the </param>
        /// <param name="guid">Open a definition from a path, without instantiating the nodes or dependents</param>
        public bool GetNodeInstance(DynamoController controller, Guid guid, out dynFunction result)
        {
            if (!this.Contains(guid))
            {
                result = null;
                return(false);
            }

            FunctionDefinition def = null;

            if (!this.IsInitialized(guid))
            {
                if (!GetDefinitionFromPath(guid, controller, out def))
                {
                    result = null;
                    return(false);
                }
            }
            else
            {
                def = this.loadedNodes[guid];
            }

            dynWorkspaceModel ws = def.Workspace;

            IEnumerable <string> inputs =
                ws.Nodes.Where(e => e is dynSymbol)
                .Select(s => (s as dynSymbol).Symbol);

            IEnumerable <string> outputs =
                ws.Nodes.Where(e => e is dynOutput)
                .Select(o => (o as dynOutput).Symbol);

            if (!outputs.Any())
            {
                var topMost = new List <Tuple <int, dynNodeModel> >();

                IEnumerable <dynNodeModel> topMostNodes = ws.GetTopMostNodes();

                foreach (dynNodeModel topNode in topMostNodes)
                {
                    foreach (int output in Enumerable.Range(0, topNode.OutPortData.Count))
                    {
                        if (!topNode.HasOutput(output))
                        {
                            topMost.Add(Tuple.Create(output, topNode));
                        }
                    }
                }

                outputs = topMost.Select(x => x.Item2.OutPortData[x.Item1].NickName);
            }

            result          = controller.DynamoViewModel.CreateFunction(inputs, outputs, def);
            result.NickName = ws.Name;

            return(true);
        }
Ejemplo n.º 17
0
        /// <summary>
        ///     The class constructor.
        /// </summary>
        /// <param name="controller"> Reference to to the DynamoController object for the app </param>
        public PackageManagerClient(DynamoController controller)
        {
            Controller = controller;

            LoadedPackageHeaders = new Dictionary<FunctionDefinition, PackageHeader>();
            Client = new Client("https://accounts-dev.autodesk.com", "http://54.243.225.192:8080");
            Worker = new BackgroundWorker();

            IsLoggedIn = false;
        }
Ejemplo n.º 18
0
        /// <summary>
        ///     Get a guid from the name of a node.  If it doesn't exist, returns Guid.Empty.
        /// </summary>
        /// <param name="guid">Open a definition from a path, without instantiating the nodes or dependents</param>
        public bool GetNodeInstance(DynamoController controller, string name, out Function result)
        {
            if (!this.Contains(name))
            {
                result = null;
                return(false);
            }

            return(this.GetNodeInstance(GetGuidFromName(name), out result));
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Enables starting Dynamo with a mock IUpdateManager
        /// </summary>
        /// <param name="updateManager"></param>
        /// <param name="watchHandler"></param>
        /// <param name="preferences"></param>
        /// <param name="visualizationManager"></param>
        protected void StartDynamo(IUpdateManager updateManager, IWatchHandler watchHandler, IPreferences preferences, IVisualizationManager visualizationManager)
        {
            var corePath =
                Path.GetFullPath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            //create a new instance of the ViewModel
            Controller = new DynamoController(Context.NONE, updateManager, watchHandler, preferences, corePath);
            Controller.DynamoViewModel      = new DynamoViewModel(Controller, null);
            DynamoController.IsTestMode     = true;
            Controller.VisualizationManager = new VisualizationManager();
        }
Ejemplo n.º 20
0
        protected void StartDynamo()
        {
            var logger        = new DynamoLogger();
            var updateManager = new UpdateManager.UpdateManager(logger);

            ////create a new instance of the ViewModel
            Controller = new DynamoController(Context.NONE, updateManager, logger,
                                              new DefaultWatchHandler(), new PreferenceSettings());
            DynamoController.IsTestMode     = true;
            Controller.DynamoViewModel      = new DynamoViewModel(Controller, null);
            Controller.VisualizationManager = new VisualizationManager();
        }
Ejemplo n.º 21
0
        protected void StartDynamo()
        {
            var logger = new DynamoLogger();
            var updateManager = new UpdateManager.UpdateManager(logger);

            ////create a new instance of the ViewModel
            Controller = new DynamoController(Context.NONE, updateManager, logger,
                new DefaultWatchHandler(), new PreferenceSettings());
            DynamoController.IsTestMode = true;
            Controller.DynamoViewModel = new DynamoViewModel(Controller, null);
            Controller.VisualizationManager = new VisualizationManager();   
        }
Ejemplo n.º 22
0
        public void Regressions(RegressionTestData testData)
        {
            Exception exception = null;

            try
            {
                var dynamoFilePath = testData.Arguments[0].ToString();
                var revitFilePath  = testData.Arguments[1].ToString();

                Setup();

                //ensure that the incoming arguments are not empty or null
                //if a dyn file is found in the regression tests directory
                //and there is no corresponding rfa or rvt, then an empty string
                //or a null will be passed into here.
                Assert.IsNotNullOrEmpty(dynamoFilePath, "Dynamo file path is invalid or missing.");
                Assert.IsNotNullOrEmpty(revitFilePath, "Revit file path is invalid or missing.");

                //open the revit model
                SwapCurrentModel(revitFilePath);

                var model = Controller.DynamoModel;

                //open the dyn file
                model.Open(dynamoFilePath);

                //run the expression and assert that it does not
                //throw an error
                Assert.DoesNotThrow(() => dynSettings.Controller.RunExpression());
                var errorNodes =
                    dynSettings.Controller.DynamoModel.Nodes.Where(
                        x => x.State == ElementState.Error || x.State == ElementState.Warning);
                Assert.AreEqual(0, errorNodes.Count());
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            finally
            {
                Controller.ShutDown(false);
                Controller = null;
                Teardown();
            }

            if (exception != null)
            {
                Assert.Fail(exception.Message);
            }
        }
Ejemplo n.º 23
0
 private void StartDynamo()
 {
     try
     {
         //create a new instance of the ViewModel
         Controller = new DynamoController(new ExecutionEnvironment(), typeof(DynamoViewModel), Context.NONE)
         {
             Testing = true
         };
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.StackTrace);
     }
 }
Ejemplo n.º 24
0
 private void StartDynamo()
 {
     try
     {
         //create a new instance of the ViewModel
         Controller = new DynamoController(new ExecutionEnvironment(), typeof(DynamoViewModel), Context.NONE)
         {
             Testing = true
         };
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.StackTrace);
     }
 }
Ejemplo n.º 25
0
        public static Application MakeSandboxAndRun(string commandFilePath)
        {
            var controller = DynamoController.MakeSandbox(commandFilePath);
            var app        = new Application();

            //create the view
            var ui = new DynamoView();

            ui.DataContext          = controller.DynamoViewModel;
            controller.UIDispatcher = ui.Dispatcher;

            app.Run(ui);

            return(app);
        }
Ejemplo n.º 26
0
        public void Regressions(RegressionTestData testData)
        {
            Exception exception = null;

            try
            {
                var dynamoFilePath = testData.Arguments[0].ToString();
                var revitFilePath = testData.Arguments[1].ToString();

                Setup();

                //ensure that the incoming arguments are not empty or null
                //if a dyn file is found in the regression tests directory
                //and there is no corresponding rfa or rvt, then an empty string
                //or a null will be passed into here.
                Assert.IsNotNullOrEmpty(dynamoFilePath, "Dynamo file path is invalid or missing.");
                Assert.IsNotNullOrEmpty(revitFilePath, "Revit file path is invalid or missing.");

                //open the revit model
                SwapCurrentModel(revitFilePath);

                //open the dyn file
                Controller.DynamoViewModel.OpenCommand.Execute(dynamoFilePath);

                //run the expression and assert that it does not
                //throw an error
                Assert.DoesNotThrow(() => dynSettings.Controller.RunExpression());
                var errorNodes =
                    dynSettings.Controller.DynamoModel.Nodes.Where(
                        x => x.State == ElementState.Error || x.State == ElementState.Warning);
                Assert.AreEqual(0, errorNodes.Count());
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            finally
            {
                Controller.ShutDown(false);
                Controller = null;
                Teardown();
            }

            if (exception != null)
            {
                Assert.Fail(exception.Message);
            }
        }
Ejemplo n.º 27
0
        public static Application MakeSandboxAndRun(string commandFilePath, bool turnOnServer)
        {
            var controller = DynamoController.MakeSandbox(commandFilePath);
            var app        = new Application();

            //create the view
            var ui = new DynamoView();

            ui.DataContext          = controller.DynamoViewModel;
            controller.UIDispatcher = ui.Dispatcher;

            if (turnOnServer)
            {
                var webSocketServer = new WebServer();
                webSocketServer.Start();
                webSocketServer.ReceivedMessage += new MessageEventHandler(dynSettings.Controller.DynamoViewModel.ExecuteMessageFromSocket);
                webSocketServer.Info            += (infoMessage) =>
                {
                    if (dynSettings.DynamoLogger != null)
                    {
                        dynSettings.DynamoLogger.Log(infoMessage);
                    }
                };
                webSocketServer.Error += (errorMessage) =>
                {
                    if (dynSettings.DynamoLogger != null)
                    {
                        dynSettings.DynamoLogger.LogError(errorMessage);
                    }
                };

                dynSettings.Controller.RequestComputationCompleted += (nodes) =>
                {
                    // TODO: Send nodes instead of nodes GUIDs
                    List <Guid> guidsList = nodes.Select(nodeModel => nodeModel.GUID).ToList();

                    webSocketServer.SendResponse(new ComputationResponse()
                    {
                        Status = ResponceStatuses.Success,
                        Nodes  = guidsList.ToArray()
                    }, dynSettings.Controller.SessionId);
                };
            }

            app.Run(ui);

            return(app);
        }
Ejemplo n.º 28
0
        public EngineController(DynamoController controller)
        {
            libraryServices = LibraryServices.GetInstance();
            libraryServices.LibraryLoading += this.LibraryLoading;
            libraryServices.LibraryLoadFailed += this.LibraryLoadFailed;
            libraryServices.LibraryLoaded += this.LibraryLoaded;

            liveRunnerServices = new LiveRunnerServices(this);
            liveRunnerServices.ReloadAllLibraries(libraryServices.Libraries.ToList());

            astBuilder = new AstBuilder(this);
            syncDataManager = new SyncDataManager();

            this.controller = controller;
            this.controller.DynamoModel.NodeDeleted += NodeDeleted;
        }
Ejemplo n.º 29
0
        public DynamoRevitViewModel(DynamoController controller) : base(controller)
        {
            Predicate <dynNodeModel> requiresTransactionPredicate = delegate(dynNodeModel node)
            {
                return(node is dynRevitTransactionNode);
            };

            checkRequiresTransaction = new PredicateTraverser(requiresTransactionPredicate);

            Predicate <dynNodeModel> manualTransactionPredicate = delegate(dynNodeModel node)
            {
                return(node is dynTransaction);
            };

            checkManualTransaction = new PredicateTraverser(manualTransactionPredicate);
        }
Ejemplo n.º 30
0
        public DynamoRevitViewModel(DynamoController controller)
            : base(controller)
        {
            Predicate<dynNodeModel> requiresTransactionPredicate = delegate(dynNodeModel node)
            {
                return node is dynRevitTransactionNode;
            };
            checkRequiresTransaction = new PredicateTraverser(requiresTransactionPredicate);

            Predicate<dynNodeModel> manualTransactionPredicate = delegate(dynNodeModel node)
            {
                return node is dynTransaction;
            };

            checkManualTransaction = new PredicateTraverser(manualTransactionPredicate);
        }
Ejemplo n.º 31
0
        public override void Cleanup()
        {
            try
            {
                Controller.ShutDown(false);
                this.Controller = null;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }

            base.Cleanup();

            GC.Collect();
        }
Ejemplo n.º 32
0
        public override void Cleanup()
        {
            try
            {
                Controller.ShutDown(false, null);
                this.Controller = null;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }

            base.Cleanup();

            GC.Collect();
        }
Ejemplo n.º 33
0
        protected void StartDynamo()
        {
            var logger = new DynamoLogger();

            dynSettings.DynamoLogger = logger;

            var updateManager = new UpdateManager.UpdateManager(logger);

            var corePath =
                Path.GetFullPath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            ////create a new instance of the ViewModel
            Controller = new DynamoController(Context.NONE, updateManager,
                                              new DefaultWatchHandler(), new PreferenceSettings(), corePath);
            DynamoController.IsTestMode     = true;
            Controller.DynamoViewModel      = new DynamoViewModel(Controller, null);
            Controller.VisualizationManager = new VisualizationManager();
        }
Ejemplo n.º 34
0
        protected void StartDynamo()
        {
            var corePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            DynamoPathManager.Instance.InitializeCore(corePath);

            var logger = new DynamoLogger(DynamoPathManager.Instance.Logs);
            dynSettings.DynamoLogger = logger;

            var updateManager = new UpdateManager.UpdateManager(logger);

            ////create a new instance of the ViewModel
            Controller = new DynamoController(Context.NONE, updateManager,
                new DefaultWatchHandler(), new PreferenceSettings(), corePath);
            DynamoController.IsTestMode = true;
            Controller.DynamoViewModel = new DynamoViewModel(Controller, null);
            Controller.VisualizationManager = new VisualizationManager();   
        }
Ejemplo n.º 35
0
        private void RecordSelectionForUndo()
        {
            // This is where we attempt to store all the models in undo recorder
            // before they are modified (i.e. being dragged around the canvas).
            // Note that we only do this once when the first mouse-move occurs
            // after a mouse-down, because mouse-down can potentially be used
            // just to select a node (as opposed to moving the selected nodes), in
            // which case we don't want any of the nodes to be recorded for undo.
            //
            List <ModelBase> models = DynamoSelection.Instance.Selection.
                                      Where((x) => (x is ModelBase)).Cast <ModelBase>().ToList <ModelBase>();

            this._model.RecordModelsForModification(models);
            DynamoController controller = Dynamo.Utilities.dynSettings.Controller;

            controller.DynamoViewModel.UndoCommand.RaiseCanExecuteChanged();
            controller.DynamoViewModel.RedoCommand.RaiseCanExecuteChanged();
        }
Ejemplo n.º 36
0
        public EngineController(DynamoController controller)
        {
            libraryServices = LibraryServices.GetInstance();
            libraryServices.LibraryLoading    += this.LibraryLoading;
            libraryServices.LibraryLoadFailed += this.LibraryLoadFailed;
            libraryServices.LibraryLoaded     += this.LibraryLoaded;

            liveRunnerServices = new LiveRunnerServices(this);
            liveRunnerServices.ReloadAllLibraries(libraryServices.Libraries.ToList());

            astBuilder      = new AstBuilder(this);
            syncDataManager = new SyncDataManager();

            this.controller = controller;
            this.controller.DynamoModel.NodeDeleted += NodeDeleted;

            this.controller.CustomNodeManager.RecompileAllNodes(this);
        }
Ejemplo n.º 37
0
        private void StartDynamo()
        {
            try
            {
                var units = new UnitsManager
                {
                    HostApplicationInternalAreaUnit   = DynamoAreaUnit.SquareFoot,
                    HostApplicationInternalLengthUnit = DynamoLengthUnit.DecimalFoot,
                    HostApplicationInternalVolumeUnit = DynamoVolumeUnit.CubicFoot
                };

                //create a new instance of the ViewModel
                Controller = new DynamoController(new ExecutionEnvironment(), typeof(DynamoViewModel), Context.NONE, new UpdateManager.UpdateManager(), units, new DefaultWatchHandler(), new PreferenceSettings());
                DynamoController.IsTestMode = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }
Ejemplo n.º 38
0
        private void RunCommandsFromFile(string commandFileName)
        {
            string commandFilePath = DynamoTestUI.GetTestDirectory();

            commandFilePath = Path.Combine(commandFilePath, @"core\recorded\");
            commandFilePath = Path.Combine(commandFilePath, commandFileName);

            // Create the controller to run alongside the view.
            controller = DynamoController.MakeSandbox(commandFilePath);

            // Create the view.
            var dynamoView = new DynamoView();

            dynamoView.DataContext  = controller.DynamoViewModel;
            controller.UIDispatcher = dynamoView.Dispatcher;
            dynamoView.ShowDialog();

            Assert.IsNotNull(controller);
            Assert.IsNotNull(controller.DynamoModel);
            Assert.IsNotNull(controller.DynamoModel.CurrentWorkspace);
            workspace = controller.DynamoModel.CurrentWorkspace;
        }
Ejemplo n.º 39
0
        public static void Main(string[] args)
        {
            //DynamoLogger.Instance.StartLogging();

            try
            {
                var controller = new DynamoController(new Dynamo.FSchemeInterop.ExecutionEnvironment(), typeof(DynamoViewModel), Context.NONE);

                //create the view
                dynSettings.Bench             = new DynamoView();
                dynSettings.Bench.DataContext = controller.DynamoViewModel;
                controller.UIDispatcher       = dynSettings.Bench.Dispatcher;

                var app = new Application();
                app.Run(dynSettings.Bench);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                Debug.WriteLine(e.StackTrace);
            }
        }
Ejemplo n.º 40
0
        protected void RunCommandsFromFile(string commandFileName,
                                           bool autoRun = false, CommandCallback commandCallback = null)
        {
            string commandFilePath = DynamoTestUI.GetTestDirectory(ExecutingDirectory);

            commandFilePath = Path.Combine(commandFilePath, @"core\recorded\");
            commandFilePath = Path.Combine(commandFilePath, commandFileName);

            if (this.Controller != null)
            {
                var message = "Multiple DynamoController detected!";
                throw new InvalidOperationException(message);
            }

            // Create the controller to run alongside the view.
            this.Controller = DynamoController.MakeSandbox(commandFilePath);
            var controller = this.Controller;

            controller.DynamoViewModel.DynamicRunEnabled = autoRun;
            DynamoController.IsTestMode = true;

            RegisterCommandCallback(commandCallback);

            // Create the view.
            var dynamoView = new DynamoView();

            dynamoView.DataContext  = controller.DynamoViewModel;
            controller.UIDispatcher = dynamoView.Dispatcher;
            dynamoView.ShowDialog();

            Assert.IsNotNull(controller);
            Assert.IsNotNull(controller.DynamoModel);
            Assert.IsNotNull(controller.DynamoModel.CurrentWorkspace);
            workspace          = controller.DynamoModel.CurrentWorkspace;
            workspaceViewModel = controller.DynamoViewModel.CurrentSpaceViewModel;
        }
Ejemplo n.º 41
0
        private void StartDynamo()
        {
            try
            {
                var updater = new RevitServicesUpdater(DynamoRevitApp.ControlledApplication, DynamoRevitApp.Updaters);
                updater.ElementAddedForID += ElementMappingCache.GetInstance().WatcherMethodForAdd;
                updater.ElementsDeleted += ElementMappingCache.GetInstance().WatcherMethodForDelete;

                SIUnit.HostApplicationInternalAreaUnit = DynamoAreaUnit.SquareFoot;
                SIUnit.HostApplicationInternalLengthUnit = DynamoLengthUnit.DecimalFoot;
                SIUnit.HostApplicationInternalVolumeUnit = DynamoVolumeUnit.CubicFoot;

                var logger = new DynamoLogger(DynamoPathManager.Instance.Logs);
                dynSettings.DynamoLogger = logger;
                var updateManager = new UpdateManager.UpdateManager(logger);

                Controller = DynamoRevit.CreateDynamoRevitControllerAndViewModel(updater, logger, Context.NONE);
                DynamoController.IsTestMode = true;

                // create the transaction manager object
                TransactionManager.SetupManager(new AutomaticTransactionStrategy());

                // Because the test framework does not work in the idle thread. 
                // We need to trick Dynamo into believing that it's in the idle
                // thread already.
                IdlePromise.InIdleThread = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }
Ejemplo n.º 42
0
 protected void StartDynamo()
 {
     ////create a new instance of the ViewModel
     Controller = new DynamoController(typeof(DynamoViewModel), Context.NONE, new UpdateManager.UpdateManager(), new DefaultWatchHandler(), new PreferenceSettings());
     DynamoController.IsTestMode = true;
 }
Ejemplo n.º 43
0
        private void StartDynamo()
        {
            try
            {
                SIUnit.HostApplicationInternalAreaUnit = DynamoAreaUnit.SquareFoot;
                SIUnit.HostApplicationInternalLengthUnit = DynamoLengthUnit.DecimalFoot;
                SIUnit.HostApplicationInternalVolumeUnit = DynamoVolumeUnit.CubicFoot;

                //create a new instance of the ViewModel
                Controller = new DynamoController(typeof (DynamoViewModel), Context.NONE, new UpdateManager.UpdateManager(), new DefaultWatchHandler(), new PreferenceSettings());
                DynamoController.IsTestMode = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }
Ejemplo n.º 44
0
        private static void StartDynamo()
        {
            try
            {

                string tempPath = Path.GetTempPath();
                var random = new Random();
                string logPath = Path.Combine(tempPath, "dynamoLog" + random.Next() + ".txt");

                TempFolder = Path.Combine(tempPath, "dynamoTmp");

                if (!Directory.Exists(TempFolder))
                {
                    Directory.CreateDirectory(TempFolder);
                }
                else
                {
                    EmptyTempFolder();
                }

                TextWriter tw = new StreamWriter(logPath);
                tw.WriteLine("Dynamo log started " + DateTime.Now.ToString());
                dynSettings.Writer = tw;

                //create a new instance of the ViewModel
                var controller = new DynamoController(new FSchemeInterop.ExecutionEnvironment());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }
Ejemplo n.º 45
0
 public MutatorDriver(DynamoController dynamoController)
 {
     this.dynamoController = dynamoController;
 }
Ejemplo n.º 46
0
        public Result Execute(ExternalCommandData revit, ref string message, ElementSet elements)
        {
            RevThread.IdlePromise.RegisterIdle(revit.Application);

            if (revit.JournalData != null && revit.JournalData.ContainsKey("debug"))
            {
                if (bool.Parse(revit.JournalData["debug"]))
                    Debugger.Launch();
            }

            AppDomain.CurrentDomain.AssemblyResolve +=
                Analyze.Render.AssemblyHelper.ResolveAssemblies;

            //Add an assembly load step for the System.Windows.Interactivity assembly
            //Revit owns a version of this as well. Adding our step here prevents a duplicative
            //load of the dll at a later time.
            string interactivityPath = Path.Combine(
                DynamoPathManager.Instance.MainExecPath,
                "System.Windows.Interactivity.dll");
            if (File.Exists(interactivityPath))
                Assembly.LoadFrom(interactivityPath);

            try
            {
                #region default level
                var fecLevel =
                    new FilteredElementCollector(revit.Application.ActiveUIDocument.Document);
                fecLevel.OfClass(typeof(Level));
                var defaultLevel = fecLevel.ToElements()[0] as Level;
                #endregion

                var logger = new DynamoLogger(DynamoPathManager.Instance.Logs);
                dynSettings.DynamoLogger = logger;

                if (DocumentManager.Instance.CurrentUIApplication == null)
                    DocumentManager.Instance.CurrentUIApplication = revit.Application;

                DocumentManager.OnLogError += dynSettings.DynamoLogger.Log;

                dynRevitSettings.DefaultLevel = defaultLevel;

                //TODO: has to be changed when we handle multiple docs
                Updater = new RevitServicesUpdater(
                    DynamoRevitApp.ControlledApplication,
                    DynamoRevitApp.Updaters);
                Updater.ElementAddedForID += ElementMappingCache.GetInstance().WatcherMethodForAdd;
                Updater.ElementsDeleted += ElementMappingCache.GetInstance().WatcherMethodForDelete;

                RevThread.IdlePromise.ExecuteOnIdleAsync(
                    delegate
                    {
                        //get window handle
                        IntPtr mwHandle = Process.GetCurrentProcess().MainWindowHandle;

                        var r = new Regex(@"\b(Autodesk |Structure |MEP |Architecture )\b");
                        string context = r.Replace(revit.Application.Application.VersionName, "");

                        //they changed the application version name conventions for vasari
                        //it no longer has a version year so we can't compare it to other versions
                        //TODO:come up with a more stable way to test for Vasari beta 3
                        if (context == "Vasari")
                            context = "Vasari 2014";

                        dynamoController = CreateDynamoRevitControllerAndViewModel(
                            Updater,
                            logger,
                            context);

                        var dynamoView = new DynamoView
                        {
                            DataContext = dynamoController.DynamoViewModel
                        };
                        dynamoController.UIDispatcher = dynamoView.Dispatcher;

                        //set window handle and show dynamo
                        new WindowInteropHelper(dynamoView).Owner = mwHandle;

                        handledCrash = false;

                        dynamoView.Show();

                        if (revit.JournalData != null && revit.JournalData.ContainsKey("dynPath"))
                            dynamoController.DynamoModel.OpenWorkspace(revit.JournalData["dynPath"]);

                        dynamoView.Dispatcher.UnhandledException += DispatcherOnUnhandledException;
                        dynamoView.Closing += dynamoView_Closing;
                        dynamoView.Closed += dynamoView_Closed;

                        revit.Application.ViewActivating += Application_ViewActivating;
                    });

                // Disable the Dynamo button to prevent a re-run
                DynamoRevitApp.DynamoButton.Enabled = false;
            }
            catch (Exception ex)
            {
                InstrumentationLogger.LogException(ex);
                StabilityTracking.GetInstance().NotifyCrash();

                //isRunning = false;
                MessageBox.Show(ex.ToString());

                dynSettings.DynamoLogger.LogError(ex.Message);
                dynSettings.DynamoLogger.LogError(ex.StackTrace);
                dynSettings.DynamoLogger.LogError("Dynamo log ended " + DateTime.Now);

                DynamoRevitApp.DynamoButton.Enabled = true;

                return Result.Failed;
            }

            return Result.Succeeded;
        }
Ejemplo n.º 47
0
        public Result Execute(ExternalCommandData revit, ref string message, ElementSet elements)
        {
            AppDomain.CurrentDomain.AssemblyResolve += Dynamo.Utilities.AssemblyHelper.CurrentDomain_AssemblyResolve;
            AppDomain.CurrentDomain.AssemblyResolve += DynamoRaaS.AssemblyHelper.ResolveAssemblies;

            //Add an assembly load step for the System.Windows.Interactivity assembly
            //Revit owns a version of this as well. Adding our step here prevents a duplicative
            //load of the dll at a later time.
            var assLoc            = Assembly.GetExecutingAssembly().Location;
            var interactivityPath = Path.Combine(Path.GetDirectoryName(assLoc), "System.Windows.Interactivity.dll");
            var interactivityAss  = Assembly.LoadFrom(interactivityPath);

            //When a user double-clicks the Dynamo icon, we need to make
            //sure that we don't create another instance of Dynamo.
            if (isRunning)
            {
                Debug.WriteLine("Dynamo is already running.");
                if (dynamoView != null)
                {
                    dynamoView.Focus();
                }
                return(Result.Succeeded);
            }

            isRunning = true;

            try
            {
                m_revit = revit.Application;
                m_doc   = m_revit.ActiveUIDocument;

                #region default level

                Level defaultLevel = null;
                var   fecLevel     = new FilteredElementCollector(m_doc.Document);
                fecLevel.OfClass(typeof(Level));
                defaultLevel = fecLevel.ToElements()[0] as Level;

                #endregion

                dynRevitSettings.Revit        = m_revit;
                dynRevitSettings.Doc          = m_doc;
                dynRevitSettings.DefaultLevel = defaultLevel;

                IdlePromise.ExecuteOnIdle(delegate
                {
                    //get window handle
                    IntPtr mwHandle = Process.GetCurrentProcess().MainWindowHandle;

                    Regex r        = new Regex(@"\b(Autodesk |Structure |MEP |Architecture )\b");
                    string context = r.Replace(m_revit.Application.VersionName, "");

                    //they changed the application version name conventions for vasari
                    //it no longer has a version year so we can't compare it to other versions
                    //TODO:come up with a more stable way to test for Vasari beta 3
                    if (context == "Vasari")
                    {
                        context = "Vasari 2014";
                    }

                    var units = new UnitsManager
                    {
                        HostApplicationInternalAreaUnit   = DynamoAreaUnit.SquareFoot,
                        HostApplicationInternalLengthUnit = DynamoLengthUnit.DecimalFoot,
                        HostApplicationInternalVolumeUnit = DynamoVolumeUnit.CubicFoot
                    };

                    dynamoController = new DynamoController_Revit(DynamoRevitApp.env, DynamoRevitApp.Updater, typeof(DynamoRevitViewModel), context, units);

                    dynamoView = new DynamoView {
                        DataContext = dynamoController.DynamoViewModel
                    };
                    dynamoController.UIDispatcher = dynamoView.Dispatcher;

                    //set window handle and show dynamo
                    new WindowInteropHelper(dynamoView).Owner = mwHandle;

                    handledCrash = false;

                    dynamoView.WindowStartupLocation = WindowStartupLocation.Manual;

                    Rectangle bounds  = Screen.PrimaryScreen.Bounds;
                    dynamoView.Left   = dynamoViewX ?? bounds.X;
                    dynamoView.Top    = dynamoViewY ?? bounds.Y;
                    dynamoView.Width  = dynamoViewWidth ?? 1000.0;
                    dynamoView.Height = dynamoViewHeight ?? 800.0;

                    dynamoView.Show();

                    dynamoView.Dispatcher.UnhandledException -= DispatcherOnUnhandledException;
                    dynamoView.Dispatcher.UnhandledException += DispatcherOnUnhandledException;
                    dynamoView.Closing += dynamoView_Closing;
                    dynamoView.Closed  += dynamoView_Closed;

                    //revit.Application.ViewActivated += new EventHandler<Autodesk.Revit.UI.Events.ViewActivatedEventArgs>(Application_ViewActivated);
                    revit.Application.ViewActivating += Application_ViewActivating;
                });
            }
            catch (Exception ex)
            {
                isRunning = false;
                MessageBox.Show(ex.ToString());

                DynamoLogger.Instance.Log(ex.Message);
                DynamoLogger.Instance.Log(ex.StackTrace);
                DynamoLogger.Instance.Log("Dynamo log ended " + DateTime.Now.ToString());

                return(Result.Failed);
            }

            return(Result.Succeeded);
        }
Ejemplo n.º 48
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, DynamoController controller, out FunctionDefinition def)
        {
            try
            {
                var xmlPath = GetNodePath(funcDefGuid);

                #region read xml file

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

                string funName = null;
                string category = "";
                double cx = dynBench.CANVAS_OFFSET_X;
                double cy = dynBench.CANVAS_OFFSET_Y;
                string id = "";

                // load the header
                foreach (XmlNode node in xmlDoc.GetElementsByTagName("dynWorkspace"))
                {
                    foreach (XmlAttribute att in node.Attributes)
                    {
                        if (att.Name.Equals("X"))
                            cx = Convert.ToDouble(att.Value);
                        else if (att.Name.Equals("Y"))
                            cy = Convert.ToDouble(att.Value);
                        else if (att.Name.Equals("Name"))
                            funName = att.Value;
                        else if (att.Name.Equals("Category"))
                            category = att.Value;
                        else if (att.Name.Equals("ID"))
                        {
                            id = 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

                //If there is no function name, then we are opening a home definition
                if (funName == null)
                {
                    //View the home workspace, then open the bench file
                    if (!controller.ViewingHomespace)
                        controller.ViewHomeWorkspace(); //TODO: Refactor
                    def = null;
                    return controller.OpenWorkbench(xmlPath);
                }

                dynSettings.Bench.Log("Loading node definition for \"" + funName + "\" from: " + xmlPath);

                var workSpace = new FuncWorkspace(
                    funName, category.Length > 0
                    ? category
                    : BuiltinNodeCategories.MISC, cx, cy);

                def = new FunctionDefinition(Guid.Parse(id))
                    {
                        Workspace = workSpace
                    };

                // 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(5);
                controller.FSchemeEnvironment.DefineSymbol(def.FunctionId.ToString(), dummyExpression);
                this.loadedNodes.Add(def.FunctionId, def);

                dynWorkspace ws = def.Workspace;

                //this.Log("Opening definition " + xmlPath + "...");

                XmlNodeList elNodes = xmlDoc.GetElementsByTagName("dynElements");
                XmlNodeList cNodes = xmlDoc.GetElementsByTagName("dynConnectors");
                XmlNodeList nNodes = xmlDoc.GetElementsByTagName("dynNotes");

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

                #region instantiate nodes

                foreach (XmlNode elNode in elNodesList.ChildNodes)
                {
                    XmlAttribute typeAttrib = elNode.Attributes[0];
                    XmlAttribute guidAttrib = elNode.Attributes[1];
                    XmlAttribute nicknameAttrib = elNode.Attributes[2];
                    XmlAttribute xAttrib = elNode.Attributes[3];
                    XmlAttribute yAttrib = elNode.Attributes[4];

                    string typeName = typeAttrib.Value;

                    string oldNamespace = "Dynamo.Elements.";
                    if (typeName.StartsWith(oldNamespace))
                        typeName = "Dynamo.Nodes." + typeName.Remove(0, oldNamespace.Length);

                    //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 = Convert.ToDouble(xAttrib.Value);
                    double y = Convert.ToDouble(yAttrib.Value);

                    //Type t = Type.GetType(typeName);
                    TypeLoadData tData;
                    Type t;

                    if (!controller.builtinTypesByTypeName.TryGetValue(typeName, out tData))
                    {
                        t = Type.GetType(typeName);
                        if (t == null)
                        {
                            dynSettings.Bench.Log("Error loading definition. Could not load node of type: " + typeName);
                            return false;
                        }
                    }
                    else
                        t = tData.Type;

                    var el = controller.CreateInstanceAndAddNodeToWorkspace(t, nickname, guid, x, y, ws, Visibility.Hidden);

                    if (el == null)
                        return false;

                    el.DisableReporting();
                    el.LoadElement(elNode); // inject the node properties from the xml

                    // it has no
                    if (el is dynFunction)
                    {
                        var fun = el as dynFunction;

                        // we've found a custom node, we need to attempt to load its guid.
                        // if it doesn't exist (i.e. its a legacy node), we need to assign it one,
                        // deterministically
                        Guid funId;
                        try
                        {
                            funId = Guid.Parse(fun.Symbol);
                        }
                        catch
                        {
                            funId = GuidUtility.Create(GuidUtility.UrlNamespace, nicknameAttrib.Value);
                            fun.Symbol = funId.ToString();
                        }

                        // if it's not a recurisve node and it's not yet loaded, load it
                        if (funcDefGuid != funId && !this.loadedNodes.ContainsKey(funId))
                        {
                            dynSettings.Controller.CustomNodeLoader.GetFunctionDefinition(funId);
                            fun.Definition = this.loadedNodes[funId];
                        }
                        else if ( this.loadedNodes.ContainsKey(funId ))
                        {
                            fun.Definition = this.loadedNodes[funId];
                        }

                    }
                }

                #endregion

                dynSettings.Bench.WorkBench.UpdateLayout();

                #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);
                    int portType = Convert.ToInt16(portTypeAttrib.Value);

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

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

                    //don't connect if the end element is an instance map
                    //those have a morphing set of inputs
                    //dynInstanceParameterMap endTest = end as dynInstanceParameterMap;

                    //if (endTest != null)
                    //{
                    //    continue;
                    //}

                    try
                    {
                        if (start != null && end != null && start != end)
                        {
                            var newConnector = new dynConnector(
                                start.NodeUI, end.NodeUI,
                                startIndex, endIndex,
                                portType, false
                                );

                            ws.Connectors.Add(newConnector);
                        }
                    }
                    catch
                    {
                        dynSettings.Bench.Log(string.Format("ERROR : Could not create connector between {0} and {1}.", start.NodeUI.GUID, end.NodeUI.GUID));
                    }
                }

                #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);
                        double y = Convert.ToDouble(yAttrib.Value);

                        //dynNote n = Bench.AddNote(text, x, y, ws);
                        //Bench.AddNote(text, x, y, ws);

                        var paramDict = new Dictionary<string, object>();
                        paramDict.Add("x", x);
                        paramDict.Add("y", y);
                        paramDict.Add("text", text);
                        paramDict.Add("workspace", ws);
                        DynamoCommands.AddNoteCmd.Execute(paramDict);
                    }
                }

                #endregion

                foreach (dynNode e in ws.Nodes)
                    e.EnableReporting();

                DynamoController.hideWorkspace(ws);

                ws.FilePath = xmlPath;

                controller.PackageManagerClient.LoadPackageHeader(def, funName);

                var expression = CompileFunction(def);
                controller.FSchemeEnvironment.DefineSymbol(def.FunctionId.ToString(), expression);

            }
            catch (Exception ex)
            {
                dynSettings.Bench.Log("There was an error opening the workbench.");
                dynSettings.Bench.Log(ex);
                controller.CleanWorkbench();
                def = null;
                return false;
            }

            return true;
        }
Ejemplo n.º 49
0
        public Result Execute(ExternalCommandData revit, ref string message, ElementSet elements)
        {
            AppDomain.CurrentDomain.AssemblyResolve += Dynamo.Utilities.AssemblyHelper.CurrentDomain_AssemblyResolve;
            AppDomain.CurrentDomain.AssemblyResolve += DynamoRaaS.AssemblyHelper.ResolveAssemblies;

            //Add an assembly load step for the System.Windows.Interactivity assembly
            //Revit owns a version of this as well. Adding our step here prevents a duplicative
            //load of the dll at a later time.
            var assLoc = Assembly.GetExecutingAssembly().Location;
            var interactivityPath = Path.Combine(Path.GetDirectoryName(assLoc), "System.Windows.Interactivity.dll");
            var interactivityAss = Assembly.LoadFrom(interactivityPath);

            //When a user double-clicks the Dynamo icon, we need to make
            //sure that we don't create another instance of Dynamo.
            if (isRunning)
            {
                Debug.WriteLine("Dynamo is already running.");
                if (dynamoView != null)
                {
                    dynamoView.Focus();
                }
                return Result.Succeeded;
            }

            isRunning = true;

            try
            {
                m_revit = revit.Application;
                m_doc = m_revit.ActiveUIDocument;

                #region default level

                Level defaultLevel = null;
                var fecLevel = new FilteredElementCollector(m_doc.Document);
                fecLevel.OfClass(typeof (Level));
                defaultLevel = fecLevel.ToElements()[0] as Level;

                #endregion

                dynRevitSettings.Revit = m_revit;
                dynRevitSettings.Doc = m_doc;
                dynRevitSettings.DefaultLevel = defaultLevel;

                IdlePromise.ExecuteOnIdle(delegate
                {
                    //get window handle
                    IntPtr mwHandle = Process.GetCurrentProcess().MainWindowHandle;

                    Regex r = new Regex(@"\b(Autodesk |Structure |MEP |Architecture )\b");
                    string context = r.Replace(m_revit.Application.VersionName, "");

                    //they changed the application version name conventions for vasari
                    //it no longer has a version year so we can't compare it to other versions
                    //TODO:come up with a more stable way to test for Vasari beta 3
                    if (context == "Vasari")
                        context = "Vasari 2014";

                    var units = new UnitsManager
                    {
                        HostApplicationInternalAreaUnit = DynamoAreaUnit.SquareFoot,
                        HostApplicationInternalLengthUnit = DynamoLengthUnit.DecimalFoot,
                        HostApplicationInternalVolumeUnit = DynamoVolumeUnit.CubicFoot
                    };

                    dynamoController = new DynamoController_Revit(DynamoRevitApp.env, DynamoRevitApp.Updater, typeof(DynamoRevitViewModel), context, units);

                    dynamoView = new DynamoView { DataContext = dynamoController.DynamoViewModel };
                    dynamoController.UIDispatcher = dynamoView.Dispatcher;

                    //set window handle and show dynamo
                    new WindowInteropHelper(dynamoView).Owner = mwHandle;

                    handledCrash = false;

                    dynamoView.WindowStartupLocation = WindowStartupLocation.Manual;

                    Rectangle bounds = Screen.PrimaryScreen.Bounds;
                    dynamoView.Left = dynamoViewX ?? bounds.X;
                    dynamoView.Top = dynamoViewY ?? bounds.Y;
                    dynamoView.Width = dynamoViewWidth ?? 1000.0;
                    dynamoView.Height = dynamoViewHeight ?? 800.0;

                    dynamoView.Show();

                    dynamoView.Dispatcher.UnhandledException -= DispatcherOnUnhandledException;
                    dynamoView.Dispatcher.UnhandledException += DispatcherOnUnhandledException;
                    dynamoView.Closing += dynamoView_Closing;
                    dynamoView.Closed += dynamoView_Closed;

                    //revit.Application.ViewActivated += new EventHandler<Autodesk.Revit.UI.Events.ViewActivatedEventArgs>(Application_ViewActivated);
                    revit.Application.ViewActivating += Application_ViewActivating;
                });
            }
            catch (Exception ex)
            {
                isRunning = false;
                MessageBox.Show(ex.ToString());

                DynamoLogger.Instance.Log(ex.Message);
                DynamoLogger.Instance.Log(ex.StackTrace);
                DynamoLogger.Instance.Log("Dynamo log ended " + DateTime.Now.ToString());

                return Result.Failed;
            }

            return Result.Succeeded;
        }
Ejemplo n.º 50
0
        /// <summary>
        ///     Get a dynFunction from a guid, also stores type internally info for future instantiation.
        ///     And add the compiled node to the enviro
        ///     As a side effect, any of its dependent nodes are also initialized.
        /// </summary>
        /// <param name="environment">The environment from which to get the </param>
        /// <param name="guid">Open a definition from a path, without instantiating the nodes or dependents</param>
        public bool GetNodeInstance(DynamoController controller, Guid guid, out dynFunction result)
        {
            if ( !this.Contains(guid) ) {
                result = null;
                return false;
            }

            FunctionDefinition def = null;
            if (!this.IsInitialized(guid))
            {
                if (!GetDefinitionFromPath(guid, controller, out def))
                {
                    result = null;
                    return false;
                }
            } else {
                def = this.loadedNodes[guid];
            }

            dynWorkspace ws = def.Workspace;

            //TODO: Update to base off of Definition

                IEnumerable<string> inputs =
                    ws.Nodes.Where(e => e is dynSymbol)
                        .Select(s => (s as dynSymbol).Symbol);

                IEnumerable<string> outputs =
                    ws.Nodes.Where(e => e is dynOutput)
                        .Select(o => (o as dynOutput).Symbol);

                if (!outputs.Any())
                {
                    var topMost = new List<Tuple<int, dynNode>>();

                    IEnumerable<dynNode> topMostNodes = ws.GetTopMostNodes();

                    foreach (dynNode topNode in topMostNodes)
                    {
                        foreach (int output in Enumerable.Range(0, topNode.OutPortData.Count))
                        {
                            if (!topNode.HasOutput(output))
                                topMost.Add(Tuple.Create(output, topNode));
                        }
                    }

                    outputs = topMost.Select(x => x.Item2.OutPortData[x.Item1].NickName);
                }

            result = new dynFunction(inputs, outputs, def);
            result.NodeUI.NickName = ws.Name;

            return true;
        }
Ejemplo n.º 51
0
        public Result Execute(ExternalCommandData revit, ref string message, ElementSet elements)
        {
            //When a user double-clicks the Dynamo icon, we need to make
            //sure that we don't create another instance of Dynamo.
            if (isRunning)
            {
                Debug.WriteLine("Dynamo is already running.");
                if (dynamoView != null)
                {
                    dynamoView.Focus();
                }
                return(Result.Succeeded);
            }

            isRunning = true;

            DynamoLogger.Instance.StartLogging();

            try
            {
                m_revit = revit.Application;
                m_doc   = m_revit.ActiveUIDocument;

                #region default level

                Level defaultLevel = null;
                var   fecLevel     = new FilteredElementCollector(m_doc.Document);
                fecLevel.OfClass(typeof(Level));
                defaultLevel = fecLevel.ToElements()[0] as Level;

                #endregion

                dynRevitSettings.Revit        = m_revit;
                dynRevitSettings.Doc          = m_doc;
                dynRevitSettings.DefaultLevel = defaultLevel;

                IdlePromise.ExecuteOnIdle(delegate
                {
                    //get window handle
                    IntPtr mwHandle = Process.GetCurrentProcess().MainWindowHandle;

                    //show the window

                    Regex r        = new Regex(@"\b(Autodesk |Structure |MEP |Architecture )\b");
                    string context = r.Replace(m_revit.Application.VersionName, "");

                    //they changed the application version name conventions for vasari
                    //it no longer has a version year so we can't compare it to other versions
                    //TODO:come up with a more stable way to test for Vasari beta 3
                    if (context == "Vasari")
                    {
                        context = "Vasari 2014";
                    }

                    dynamoController = new DynamoController_Revit(DynamoRevitApp.env, DynamoRevitApp.updater, typeof(DynamoRevitViewModel), context);

                    dynSettings.Bench = new DynamoView {
                        DataContext = dynamoController.DynamoViewModel
                    };
                    dynamoController.UIDispatcher = dynSettings.Bench.Dispatcher;
                    dynamoView = dynSettings.Bench;

                    //set window handle and show dynamo
                    new WindowInteropHelper(dynamoView).Owner = mwHandle;

                    handledCrash = false;

                    dynamoView.WindowStartupLocation = WindowStartupLocation.Manual;

                    Rectangle bounds  = Screen.PrimaryScreen.Bounds;
                    dynamoView.Left   = dynamoViewX ?? bounds.X;
                    dynamoView.Top    = dynamoViewY ?? bounds.Y;
                    dynamoView.Width  = dynamoViewWidth ?? 1000.0;
                    dynamoView.Height = dynamoViewHeight ?? 800.0;

                    dynamoView.Show();
                    dynamoView.Dispatcher.UnhandledException += DispatcherOnUnhandledException;
                    dynamoView.Closing += dynamoView_Closing;
                    dynamoView.Closed  += dynamoView_Closed;
                });
            }
            catch (Exception ex)
            {
                isRunning = false;
                MessageBox.Show(ex.ToString());

                DynamoLogger.Instance.Log(ex.Message);
                DynamoLogger.Instance.Log(ex.StackTrace);
                DynamoLogger.Instance.Log("Dynamo log ended " + DateTime.Now.ToString());

                return(Result.Failed);
            }

            return(Result.Succeeded);
        }
Ejemplo n.º 52
0
        private static void StartDynamo()
        {
            try
            {
                ExecutingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                string tempPath = Path.GetTempPath();

                TempFolder = Path.Combine(tempPath, "dynamoTmp");

                if (!Directory.Exists(TempFolder))
                {
                    Directory.CreateDirectory(TempFolder);
                }
                else
                {
                    EmptyTempFolder();
                }

                DynamoLogger.Instance.StartLogging();

                //create a new instance of the ViewModel
                controller = new DynamoController(new FSchemeInterop.ExecutionEnvironment(), false, typeof(DynamoViewModel), Context.NONE);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }
Ejemplo n.º 53
0
        /// <summary>
        ///     Enumerate the types in an assembly and add them to DynamoController's
        ///     dictionaries and the search view model.  Internally catches exceptions and sends the error 
        ///     to the console.
        /// </summary>
        /// <param name="searchViewModel">The searchViewModel to which the nodes will be added</param>
        /// <param name="controller">The DynamoController, whose dictionaries will be modified</param>
        /// <param name="bench">The bench where logging errors will be sent</param>
        private static void LoadNodesFromAssembly(Assembly assembly, SearchViewModel searchViewModel, DynamoController controller)
        {
            try
            {
                Type[] loadedTypes = assembly.GetTypes();

                foreach (Type t in loadedTypes)
                {
                    try
                    {
                        //only load types that are in the right namespace, are not abstract
                        //and have the elementname attribute
                        object[] attribs = t.GetCustomAttributes(typeof (NodeNameAttribute), false);

                        if (IsNodeSubType(t) && attribs.Length > 0)
                        {
                            //if we are running in revit (or any context other than NONE) use the DoNotLoadOnPlatforms attribute,
                            //if available, to discern whether we should load this type
                            if (!controller.Context.Equals(Context.NONE))
                            {
                                object[] platformExclusionAttribs = t.GetCustomAttributes(typeof(DoNotLoadOnPlatformsAttribute), false);
                                if (platformExclusionAttribs.Length > 0)
                                {
                                    string[] exclusions = (platformExclusionAttribs[0] as DoNotLoadOnPlatformsAttribute).Values;
                                    if (exclusions.Contains(controller.Context))
                                        //if the attribute's values contain the context stored on the controller
                                        //then skip loading this type.
                                        continue;
                                }
                            }

                            searchViewModel.Add(t);
                            string typeName = (attribs[0] as NodeNameAttribute).Name;
                            var data = new TypeLoadData(assembly, t);

                            if (!controller.BuiltInTypesByNickname.ContainsKey(typeName))
                            {
                                controller.BuiltInTypesByNickname.Add(typeName, data);
                            }
                            else
                            {
                                dynSettings.Controller.DynamoViewModel.Log("Duplicate type encountered: " + typeName);
                            }

                            if (!controller.BuiltInTypesByName.ContainsKey(t.FullName))
                            {
                                controller.BuiltInTypesByName.Add(t.FullName, data);
                            }
                            else
                            {
                                dynSettings.Controller.DynamoViewModel.Log("Duplicate type encountered: " + typeName);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        dynSettings.Controller.DynamoViewModel.Log("Failed to load type from " + assembly.FullName);
                        dynSettings.Controller.DynamoViewModel.Log("The type was " + t.FullName);
                        dynSettings.Controller.DynamoViewModel.Log(e);
                    }

                }
            }
            catch (Exception e)
            {
                dynSettings.Controller.DynamoViewModel.Log("Could not load types.");
                dynSettings.Controller.DynamoViewModel.Log(e);
                if (e is ReflectionTypeLoadException)
                {
                    var typeLoadException = e as ReflectionTypeLoadException;
                    Exception[] loaderExceptions = typeLoadException.LoaderExceptions;
                    dynSettings.Controller.DynamoViewModel.Log("Dll Load Exception: " + loaderExceptions[0]);
                    dynSettings.Controller.DynamoViewModel.Log(loaderExceptions[0].ToString());
                    if (loaderExceptions.Count() > 1)
                    {
                        dynSettings.Controller.DynamoViewModel.Log("Dll Load Exception: " + loaderExceptions[1]);
                        dynSettings.Controller.DynamoViewModel.Log(loaderExceptions[1].ToString());
                    }
                }
            }
        }
Ejemplo n.º 54
0
        /// <summary>
        ///     Enumerate local library assemblies and add them to DynamoController's
        ///     dictionaries and search.  
        /// </summary>
        /// <param name="searchViewModel">The searchViewModel to which the nodes will be added</param>
        /// <param name="controller">The DynamoController, whose dictionaries will be modified</param>
        internal static void LoadBuiltinTypes(SearchViewModel searchViewModel, DynamoController controller)
        {
            Assembly dynamoAssembly = Assembly.GetExecutingAssembly();

            string location = Path.GetDirectoryName(dynamoAssembly.Location);

            #region determine assemblies to load

            var allLoadedAssembliesByPath = new Dictionary<string, Assembly>();
            var allLoadedAssemblies = new Dictionary<string, Assembly>();

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                allLoadedAssembliesByPath[assembly.Location] = assembly;
                allLoadedAssemblies[assembly.FullName] = assembly;
            }

            string path = Path.Combine(location, "packages");

            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            IEnumerable<string> allDynamoAssemblyPaths =
                Directory.GetFiles(location, "*.dll")
                         .Concat(Directory.GetFiles(
                             path,
                             "*.dll",
                             SearchOption.AllDirectories));

            var resolver = new ResolveEventHandler(delegate(object sender, ResolveEventArgs args)
            {
                Assembly result;
                allLoadedAssemblies.TryGetValue(args.Name, out result);
                return result;
            });

            AppDomain.CurrentDomain.AssemblyResolve += resolver;

            foreach (string assemblyPath in allDynamoAssemblyPaths)
            {
                if (allLoadedAssembliesByPath.ContainsKey(assemblyPath))
                    LoadNodesFromAssembly(allLoadedAssembliesByPath[assemblyPath], searchViewModel, controller);
                else
                {
                    try
                    {
                        Assembly assembly = Assembly.LoadFrom(assemblyPath);
                        allLoadedAssemblies[assembly.GetName().Name] = assembly;
                        LoadNodesFromAssembly(assembly, searchViewModel, controller);
                    }
                    catch
                    {
                    }
                }
            }

            AppDomain.CurrentDomain.AssemblyResolve -= resolver;

            #endregion
        }
Ejemplo n.º 55
0
 public DynamoRevitViewModel(DynamoController controller, string commandFilePath)
     : base(controller, commandFilePath)
 {
 }
Ejemplo n.º 56
0
        public DynamoViewModel(DynamoController controller)
        {
            ConnectorType = ConnectorType.BEZIER;

            //create the model
            _model = new DynamoModel();
            dynSettings.Controller.DynamoModel = _model;

            //register for property change notifications
            //on the model and the controller
            _model.PropertyChanged += _model_PropertyChanged;
            dynSettings.Controller.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(Controller_PropertyChanged);
            _model.Workspaces.CollectionChanged    += Workspaces_CollectionChanged;

            _model.AddHomeWorkspace();
            _model.CurrentSpace = _model.HomeSpace;

            Controller = controller;

            OpenCommand = new DelegateCommand(_model.Open, _model.CanOpen);
            ShowOpenDialogAndOpenResultCommand = new DelegateCommand(_model.ShowOpenDialogAndOpenResult, _model.CanShowOpenDialogAndOpenResultCommand);
            WriteToLogCmd                = new DelegateCommand(_model.WriteToLog, _model.CanWriteToLog);
            PostUiActivationCommand      = new DelegateCommand(_model.PostUIActivation, _model.CanDoPostUIActivation);
            AddNoteCommand               = new DelegateCommand(_model.AddNote, _model.CanAddNote);
            LayoutAllCommand             = new DelegateCommand(_model.LayoutAll, _model.CanLayoutAll);
            AddToSelectionCommand        = new DelegateCommand(_model.AddToSelection, _model.CanAddToSelection);
            ShowNewFunctionDialogCommand = new DelegateCommand(_model.ShowNewFunctionDialogAndMakeFunction, _model.CanShowNewFunctionDialogCommand);
            CreateNodeCommand            = new DelegateCommand(_model.CreateNode, _model.CanCreateNode);
            CreateConnectionCommand      = new DelegateCommand(_model.CreateConnection, _model.CanCreateConnection);
            ClearCommand     = new DelegateCommand(_model.Clear, _model.CanClear);
            GoHomeCommand    = new DelegateCommand(GoHomeView, CanGoHomeView);
            SelectAllCommand = new DelegateCommand(SelectAll, CanSelectAll);
            ShowSaveDialogAndSaveResultCommand = new DelegateCommand(ShowSaveDialogAndSaveResult, CanShowSaveDialogAndSaveResult);
            SaveCommand                                = new DelegateCommand(_model.Save, _model.CanSave);
            SaveAsCommand                              = new DelegateCommand(_model.SaveAs, _model.CanSaveAs);
            HomeCommand                                = new DelegateCommand(_model.Home, _model.CanGoHome);
            NewHomeWorkspaceCommand                    = new DelegateCommand(MakeNewHomeWorkspace, CanMakeNewHomeWorkspace);
            GoToWorkspaceCommand                       = new DelegateCommand(GoToWorkspace, CanGoToWorkspace);
            DeleteCommand                              = new DelegateCommand(_model.Delete, _model.CanDelete);
            ExitCommand                                = new DelegateCommand(Exit, CanExit);
            ToggleFullscreenWatchShowingCommand        = new DelegateCommand(ToggleFullscreenWatchShowing, CanToggleFullscreenWatchShowing);
            ToggleCanNavigateBackgroundCommand         = new DelegateCommand(ToggleCanNavigateBackground, CanToggleCanNavigateBackground);
            AlignSelectedCommand                       = new DelegateCommand(AlignSelected, CanAlignSelected);;
            ShowSaveDialogIfNeededAndSaveResultCommand = new DelegateCommand(ShowSaveDialogIfNeededAndSaveResult, CanShowSaveDialogIfNeededAndSaveResultCommand);
            RefactorCustomNodeCommand                  = new DelegateCommand(_model.RefactorCustomNode, _model.CanRefactorCustomNode);
            SaveImageCommand                           = new DelegateCommand(SaveImage, CanSaveImage);
            ShowSaveImageDialogAndSaveResultCommand    = new DelegateCommand(ShowSaveImageDialogAndSaveResult, CanShowSaveImageDialogAndSaveResult);
            CopyCommand                                = new DelegateCommand(_model.Copy, _model.CanCopy);
            PasteCommand                               = new DelegateCommand(_model.Paste, _model.CanPaste);
            ToggleConsoleShowingCommand                = new DelegateCommand(ToggleConsoleShowing, CanToggleConsoleShowing);
            CancelRunCommand                           = new DelegateCommand(Controller.CancelRun, Controller.CanCancelRun);
            RunExpressionCommand                       = new DelegateCommand(Controller.RunExpression, Controller.CanRunExpression);
            DisplayFunctionCommand                     = new DelegateCommand(Controller.DisplayFunction, Controller.CanDisplayFunction);
            SetConnectorTypeCommand                    = new DelegateCommand(SetConnectorType, CanSetConnectorType);
            ReportABugCommand                          = new DelegateCommand(Controller.ReportABug, Controller.CanReportABug);
            GoToWikiCommand                            = new DelegateCommand(GoToWiki, CanGoToWiki);
            GoToSourceCodeCommand                      = new DelegateCommand(GoToSourceCode, CanGoToSourceCode);

            ShowPackageManagerSearchCommand = new DelegateCommand(ShowPackageManagerSearch, CanShowPackageManagerSearch);
            ShowInstalledPackagesCommand    = new DelegateCommand(ShowInstalledPackages, CanShowInstalledPackages);
            PublishCurrentWorkspaceCommand  = new DelegateCommand(PublishCurrentWorkspace, CanPublishCurrentWorkspace);
            PublishSelectedNodesCommand     = new DelegateCommand(PublishSelectedNodes, CanPublishSelectedNodes);

            ShowHideConnectorsCommand = new DelegateCommand(ShowConnectors, CanShowConnectors);
            SelectNeighborsCommand    = new DelegateCommand(SelectNeighbors, CanSelectNeighbors);
            ClearLogCommand           = new DelegateCommand(dynSettings.Controller.ClearLog, dynSettings.Controller.CanClearLog);
            PanCommand = new DelegateCommand(Pan, CanPan);

            DynamoLogger.Instance.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(Instance_PropertyChanged);

            DynamoSelection.Instance.Selection.CollectionChanged += SelectionOnCollectionChanged;
        }
Ejemplo n.º 57
0
        /// <summary>
        ///     Get a guid from the name of a node.  If it doesn't exist, returns Guid.Empty.
        /// </summary>
        /// <param name="guid">Open a definition from a path, without instantiating the nodes or dependents</param>
        public bool GetNodeInstance(DynamoController controller, string name, out Function result)
        {
            if (!Contains(name))
            {
                result = null;
                return false;
            }

            return GetNodeInstance(GetGuidFromName(name), out result);
        }
Ejemplo n.º 58
0
 /// <summary>
 /// Enables starting Dynamo with a mock IUpdateManager
 /// </summary>
 /// <param name="updateManager"></param>
 protected void StartDynamo(IUpdateManager updateManager, IWatchHandler watchHandler, IPreferences preferences)
 {
     //create a new instance of the ViewModel
     Controller = new DynamoController(typeof(DynamoViewModel), Context.NONE, updateManager, watchHandler, preferences);
     DynamoController.IsTestMode = true;
 }
Ejemplo n.º 59
0
        public DynamoViewModel(DynamoController controller, string commandFilePath)
        {
            //create the model
            _model = new DynamoModel();
            dynSettings.Controller.DynamoModel = _model;

            //register for property change notifications
            //on the model and the controller
            _model.PropertyChanged += _model_PropertyChanged;
            dynSettings.Controller.PropertyChanged += Controller_PropertyChanged;
            _model.Workspaces.CollectionChanged += Workspaces_CollectionChanged;

            _model.AddHomeWorkspace();
            _model.CurrentWorkspace = _model.HomeSpace;

            Controller = controller;

            //Register for a notification when the update manager downloads an update
            dynSettings.Controller.UpdateManager.UpdateDownloaded += Instance_UpdateDownloaded;

            // Instantiate an AutomationSettings to handle record/playback.
            automationSettings = new AutomationSettings(this, commandFilePath);

            OpenCommand = new DelegateCommand(_model.Open, _model.CanOpen);
            ShowOpenDialogAndOpenResultCommand = new DelegateCommand(_model.ShowOpenDialogAndOpenResult, _model.CanShowOpenDialogAndOpenResultCommand);
            WriteToLogCmd = new DelegateCommand(_model.WriteToLog, _model.CanWriteToLog);
            PostUiActivationCommand = new DelegateCommand(_model.PostUIActivation, _model.CanDoPostUIActivation);
            AddNoteCommand = new DelegateCommand(_model.AddNote, _model.CanAddNote);
            AddToSelectionCommand = new DelegateCommand(_model.AddToSelection, _model.CanAddToSelection);
            ShowNewFunctionDialogCommand = new DelegateCommand(_model.ShowNewFunctionDialogAndMakeFunction, _model.CanShowNewFunctionDialogCommand);
            SaveRecordedCommand = new DelegateCommand(SaveRecordedCommands, CanSaveRecordedCommands);
            InsertPausePlaybackCommand = new DelegateCommand(ExecInsertPausePlaybackCommand, CanInsertPausePlaybackCommand);
            GoHomeCommand = new DelegateCommand(GoHomeView, CanGoHomeView);
            SelectAllCommand = new DelegateCommand(SelectAll, CanSelectAll);
            ShowSaveDialogAndSaveResultCommand = new DelegateCommand(ShowSaveDialogAndSaveResult, CanShowSaveDialogAndSaveResult);
            SaveCommand = new DelegateCommand(_model.Save, _model.CanSave);
            SaveAsCommand = new DelegateCommand(_model.SaveAs, _model.CanSaveAs);
            HomeCommand = new DelegateCommand(_model.Home, _model.CanGoHome);
            NewHomeWorkspaceCommand = new DelegateCommand(MakeNewHomeWorkspace, CanMakeNewHomeWorkspace);
            GoToWorkspaceCommand = new DelegateCommand(GoToWorkspace, CanGoToWorkspace);
            DeleteCommand = new DelegateCommand(_model.Delete, _model.CanDelete);
            ExitCommand = new DelegateCommand(Exit, CanExit);
            ToggleFullscreenWatchShowingCommand = new DelegateCommand(ToggleFullscreenWatchShowing, CanToggleFullscreenWatchShowing);
            ToggleCanNavigateBackgroundCommand = new DelegateCommand(ToggleCanNavigateBackground, CanToggleCanNavigateBackground);
            AlignSelectedCommand = new DelegateCommand(AlignSelected, CanAlignSelected); ;
            ShowSaveDialogIfNeededAndSaveResultCommand = new DelegateCommand(ShowSaveDialogIfNeededAndSaveResult, CanShowSaveDialogIfNeededAndSaveResultCommand);
            SaveImageCommand = new DelegateCommand(SaveImage, CanSaveImage);
            ShowSaveImageDialogAndSaveResultCommand = new DelegateCommand(ShowSaveImageDialogAndSaveResult, CanShowSaveImageDialogAndSaveResult);
            UndoCommand = new DelegateCommand(Undo, CanUndo);
            RedoCommand = new DelegateCommand(Redo, CanRedo);
            CopyCommand = new DelegateCommand(_model.Copy, _model.CanCopy);
            PasteCommand = new DelegateCommand(_model.Paste, _model.CanPaste);
            ToggleConsoleShowingCommand = new DelegateCommand(ToggleConsoleShowing, CanToggleConsoleShowing);
            CancelRunCommand = new DelegateCommand(Controller.CancelRunCmd, Controller.CanCancelRunCmd);
            RunExpressionCommand = new DelegateCommand(Controller.RunExprCmd, Controller.CanRunExprCmd);
            DisplayFunctionCommand = new DelegateCommand(Controller.DisplayFunction, Controller.CanDisplayFunction);
            SetConnectorTypeCommand = new DelegateCommand(SetConnectorType, CanSetConnectorType);
            ReportABugCommand = new DelegateCommand(Controller.ReportABug, Controller.CanReportABug);
            GoToWikiCommand = new DelegateCommand(GoToWiki, CanGoToWiki);
            GoToSourceCodeCommand = new DelegateCommand(GoToSourceCode, CanGoToSourceCode);
            ShowPackageManagerSearchCommand = new DelegateCommand(ShowPackageManagerSearch, CanShowPackageManagerSearch);
            ShowInstalledPackagesCommand = new DelegateCommand(ShowInstalledPackages, CanShowInstalledPackages);
            PublishCurrentWorkspaceCommand = new DelegateCommand(PublishCurrentWorkspace, CanPublishCurrentWorkspace);
            PublishSelectedNodesCommand = new DelegateCommand(PublishSelectedNodes, CanPublishSelectedNodes);
            ShowHideConnectorsCommand = new DelegateCommand(ShowConnectors, CanShowConnectors);
            SelectNeighborsCommand = new DelegateCommand(SelectNeighbors, CanSelectNeighbors);
            ClearLogCommand = new DelegateCommand(dynSettings.Controller.ClearLog, dynSettings.Controller.CanClearLog);
            PanCommand = new DelegateCommand(Pan, CanPan);
            ZoomInCommand = new DelegateCommand(ZoomIn, CanZoomIn);
            ZoomOutCommand = new DelegateCommand(ZoomOut, CanZoomOut);
            FitViewCommand = new DelegateCommand(FitView, CanFitView);
            TogglePanCommand = new DelegateCommand(TogglePan, CanTogglePan);
            EscapeCommand = new DelegateCommand(Escape, CanEscape);
            SelectVisualizationInViewCommand = new DelegateCommand(SelectVisualizationInView, CanSelectVisualizationInView);
            GetBranchVisualizationCommand = new DelegateCommand(GetBranchVisualization, CanGetBranchVisualization);
            TogglePreviewBubbleVisibilityCommand = new DelegateCommand(TogglePreviewBubbleVisibility, CanTogglePreviewBubbleVisibility);
            ExportToSTLCommand = new DelegateCommand(ExportToSTL, CanExportToSTL);
            ImportLibraryCommand = new DelegateCommand(ImportLibrary, CanImportLibrary);
            SetLengthUnitCommand = new DelegateCommand(SetLengthUnit, CanSetLengthUnit);
            SetAreaUnitCommand = new DelegateCommand(SetAreaUnit, CanSetAreaUnit);
            SetVolumeUnitCommand = new DelegateCommand(SetVolumeUnit, CanSetVolumeUnit);
            ShowAboutWindowCommand = new DelegateCommand(ShowAboutWindow, CanShowAboutWindow);
            CheckForUpdateCommand = new DelegateCommand(CheckForUpdate, CanCheckForUpdate);
            SetNumberFormatCommand = new DelegateCommand(SetNumberFormat, CanSetNumberFormat);

            DynamoLogger.Instance.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(Instance_PropertyChanged);

            DynamoSelection.Instance.Selection.CollectionChanged += SelectionOnCollectionChanged;
            dynSettings.Controller.VisualizationManager.PropertyChanged += VisualizationManager_PropertyChanged;

            this.Model.PropertyChanged += (e, args) =>
            {
                if (args.PropertyName == "CurrentWorkspace" && dynSettings.Controller.DynamoModel.CurrentWorkspace != null)
                {
                    var visibleWorkspace =
                        (dynSettings.Controller.DynamoModel.CurrentWorkspace is CustomNodeWorkspaceModel);

                    dynSettings.Controller.SearchViewModel.SearchElements
                        .Where(x => x.Name == "Input" || x.Name == "Output")
                        .OfType<NodeSearchElement>()
                        .ToList()
                        .ForEach(x => x.SetSearchable(visibleWorkspace));

                    dynSettings.Controller.SearchViewModel.SearchAndUpdateResultsSync();
                }
            };

            UsageReportingManager.Instance.PropertyChanged += CollectInfoManager_PropertyChanged;

            WatchIsResizable = false;
        }
Ejemplo n.º 60
0
 public MutatorDriver(DynamoController dynamoController)
 {
     this.dynamoController = dynamoController;
 }