Interaction logic for DynamoForm.xaml
Inheritance: System.Windows.Window, IDisposable
Exemplo n.º 1
0
        public void RunApplication(Application app)
        {
            try
            {
                DynamoModel.RequestMigrationStatusDialog += MigrationStatusDialogRequested;

                var model = Dynamo.Applications.StartupUtils.MakeModel(false);

                viewModel = DynamoViewModel.Start(
                    new DynamoViewModel.StartConfiguration()
                    {
                        CommandFilePath = commandFilePath,
                        DynamoModel = model,
                        Watch3DViewModel = HelixWatch3DViewModel.TryCreateHelixWatch3DViewModel(new Watch3DViewModelStartupParams(model), model.Logger),
                        ShowLogin = true
                    });

                var view = new DynamoView(viewModel);
                view.Loaded += (sender, args) => CloseMigrationWindow();

                app.Run(view);

                DynamoModel.RequestMigrationStatusDialog -= MigrationStatusDialogRequested;

            }

            catch (Exception e)
            {
                try
                {
#if DEBUG
                    // Display the recorded command XML when the crash happens, 
                    // so that it maybe saved and re-run later
                    if (viewModel != null)
                        viewModel.SaveRecordedCommand.Execute(null);
#endif

                    DynamoModel.IsCrashing = true;
                    InstrumentationLogger.LogException(e);
                    StabilityTracking.GetInstance().NotifyCrash();

                    if (viewModel != null)
                    {
                        // Show the unhandled exception dialog so user can copy the 
                        // crash details and report the crash if she chooses to.
                        viewModel.Model.OnRequestsCrashPrompt(null,
                            new CrashPromptArgs(e.Message + "\n\n" + e.StackTrace));

                        // Give user a chance to save (but does not allow cancellation)
                        viewModel.Exit(allowCancel: false);
                    }
                }
                catch
                {
                }

                Debug.WriteLine(e.Message);
                Debug.WriteLine(e.StackTrace);
            }
        }
Exemplo n.º 2
0
        private static void MakeStandaloneAndRun(string commandFilePath, ref DynamoViewModel viewModel)
        {
            DynamoPathManager.Instance.InitializeCore(
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            DynamoPathManager.PreloadAsmLibraries(DynamoPathManager.Instance);
            
            var model = DynamoModel.Start(
                new DynamoModel.StartConfiguration()
                {
                    Preferences = PreferenceSettings.Load()
                });

            viewModel = DynamoViewModel.Start(
                new DynamoViewModel.StartConfiguration()
                {
                    CommandFilePath = commandFilePath,
                    DynamoModel = model
                });

            var view = new DynamoView(viewModel);

            var app = new Application();
            app.Run(view);
        }
        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;
            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();
            }
        }
Exemplo n.º 4
0
        private void Init(IUpdateManager updateManager, ILogger logger)
        {
            AppDomain.CurrentDomain.AssemblyResolve += AssemblyHelper.CurrentDomain_AssemblyResolve;

            Controller = new DynamoController("None", updateManager, logger,
                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);
            }
        }
Exemplo n.º 5
0
        public virtual void Start()
        {
            AppDomain.CurrentDomain.AssemblyResolve += AssemblyHelper.CurrentDomain_AssemblyResolve;

            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());
        }
Exemplo n.º 6
0
        private void Init()
        {
            AppDomain.CurrentDomain.AssemblyResolve += AssemblyHelper.ResolveAssembly;

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

            Model = DynamoModel.Start(
                new DynamoModel.StartConfiguration()
                {
                    StartInTestMode = true,
                    DynamoCorePath = corePath
                });

            ViewModel = DynamoViewModel.Start(
                new DynamoViewModel.StartConfiguration()
                {
                    DynamoModel = Model
                });

            //create the view
            View = new DynamoView(ViewModel);
            View.Show();                             

            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
            CreateTemporaryFolder();
        }
Exemplo n.º 7
0
 internal ViewLoadedParams(DynamoView dynamoV, DynamoViewModel dynamoVM) :
     base(dynamoVM.Model)
 {
     dynamoView = dynamoV;
     dynamoViewModel = dynamoVM;
     dynamoMenu = dynamoView.titleBar.ChildOfType<Menu>();
 }
Exemplo n.º 8
0
        public virtual void Start()
        {
            DynamoPathManager.Instance.InitializeCore(
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            DynamoPathManager.PreloadAsmLibraries(DynamoPathManager.Instance);

            AppDomain.CurrentDomain.AssemblyResolve += AssemblyHelper.ResolveAssembly;
            CreateTemporaryFolder();

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

            Model = DynamoModel.Start(
                new DynamoModel.StartConfiguration()
                {
                    StartInTestMode = true
                });

            ViewModel = DynamoViewModel.Start(
                new DynamoViewModel.StartConfiguration()
                {
                    DynamoModel = Model
                });

            //create the view
            View = new DynamoView(ViewModel);
            View.Show();

            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
        }
Exemplo n.º 9
0
        internal ViewLoadedParams(DynamoView dynamoV, DynamoViewModel dynamoVM) :
            base(dynamoVM.Model)
        {
            dynamoView = dynamoV;
            dynamoViewModel = dynamoVM;
            dynamoMenu = dynamoView.titleBar.ChildOfType<Menu>();

            DynamoSelection.Instance.Selection.CollectionChanged += OnSelectionCollectionChanged;
        }
Exemplo n.º 10
0
        /// <summary>
        ///     Setup the "Samples" sub-menu with contents of samples directory.
        /// </summary>
        /// <param name="bench">The bench where the UI will be loaded</param>
        public static void LoadSamplesMenu(DynamoView bench)
        {
            string directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string samplesPath = Path.Combine(directory, "samples");

            if (Directory.Exists(samplesPath))
            {
                string[] dirPaths = Directory.GetDirectories(samplesPath);
                string[] filePaths = Directory.GetFiles(samplesPath, "*.dyn");

                // handle top-level files
                if (filePaths.Any())
                {
                    foreach (string path in filePaths)
                    {
                        var item = new MenuItem
                        {
                            Header = Path.GetFileNameWithoutExtension(path),
                            Tag = path
                        };
                        item.Click += OpenSample_Click;
                        bench.SamplesMenu.Items.Add(item);
                    }
                }

                // handle top-level dirs, TODO - factor out to a seperate function, make recusive
                if (dirPaths.Any())
                {
                    foreach (string dirPath in dirPaths)
                    {
                        var dirItem = new MenuItem
                        {
                            Header = Path.GetFileName(dirPath),
                            Tag = Path.GetFileName(dirPath)
                        };

                        filePaths = Directory.GetFiles(dirPath, "*.dyn");
                        if (filePaths.Any())
                        {
                            foreach (string path in filePaths)
                            {
                                var item = new MenuItem
                                {
                                    Header = Path.GetFileNameWithoutExtension(path),
                                    Tag = path
                                };
                                item.Click += OpenSample_Click;
                                dirItem.Items.Add(item);
                            }
                        }
                        bench.SamplesMenu.Items.Add(dirItem);
                    }
                    return;
                }
            }
            //this.fileMenu.Items.Remove(this.samplesMenu);
        }
Exemplo n.º 11
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;
        }
Exemplo n.º 12
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);
        }
Exemplo n.º 13
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);
        }
Exemplo n.º 14
0
        public virtual void Start()
        {
            var assemblyPath = Assembly.GetExecutingAssembly().Location;
            preloader = new Preloader(Path.GetDirectoryName(assemblyPath));
            preloader.Preload();
            CreateTemporaryFolder();

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

            TestPathResolver pathResolver = null;
            var preloadedLibraries = new List<string>();
            GetLibrariesToPreload(preloadedLibraries);

            if (preloadedLibraries.Any())
            {
                // Only when any library needs preloading will a path resolver be 
                // created, otherwise DynamoModel gets created without preloading 
                // any library.
                // 
                pathResolver = new TestPathResolver();
                foreach (var preloadedLibrary in preloadedLibraries.Distinct())
                {
                    pathResolver.AddPreloadLibraryPath(preloadedLibrary);
                }
            }

            Model = DynamoModel.Start(
                new DynamoModel.DefaultStartConfiguration()
                {
                    StartInTestMode = true,
                    PathResolver = pathResolver,
                    GeometryFactoryPath = preloader.GeometryFactoryPath,
                    ProcessMode = TaskProcessMode.Synchronous
                });

            ViewModel = DynamoViewModel.Start(
                new DynamoViewModel.StartConfiguration()
                {
                    DynamoModel = Model
                });

            //create the view
            View = new DynamoView(ViewModel);
            View.Show();

            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
        }
        public InCanvasSearchControl()
        {
            InitializeComponent();

            this.Loaded += (sender, e) =>
            {
                if (workspaceView == null)
                    workspaceView = WpfUtilities.FindUpVisualTree<WorkspaceView>(this.Parent);
                if (dynamoView == null)
                {
                    dynamoView = WpfUtilities.FindUpVisualTree<DynamoView>(this.Parent);
                    if (dynamoView != null)
                        dynamoView.Deactivated += (s, args) => { OnRequestShowInCanvasSearch(ShowHideFlags.Hide); };
                }
            };
        }
Exemplo n.º 16
0
        private static void MakeStandaloneAndRun(string commandFilePath, out DynamoViewModel viewModel)
        {
            var model = Dynamo.Applications.StartupUtils.MakeModel(false);
            DynamoModel.RequestMigrationStatusDialog += MigrationStatusDialogRequested;

            viewModel = DynamoViewModel.Start(
                new DynamoViewModel.StartConfiguration()
                {
                    CommandFilePath = commandFilePath,
                    DynamoModel = model
                });

            var view = new DynamoView(viewModel);
            view.Loaded += (sender, args) => CloseMigrationWindow();

            var app = new Application();
            app.Run(view);

            DynamoModel.RequestMigrationStatusDialog -= MigrationStatusDialogRequested;
        }
Exemplo n.º 17
0
        /// <summary>
        ///     Load Custom Nodes from the default directory - the "definitions"
        ///     directory where the executing assembly is located..
        /// </summary>
        /// <param name="bench">The logger is needed in order to tell how long it took.</param>
        public static void LoadCustomNodes(DynamoView bench, CustomNodeLoader customNodeLoader, SearchViewModel searchViewModel)
        {
            // custom node loader
            var sw = new Stopwatch();
            sw.Start();

            customNodeLoader.UpdateSearchPath();
            var nn = customNodeLoader.GetNodeNameCategoryAndGuidList();

            // add nodes to search
            foreach (var pair in nn)
            {
                searchViewModel.Add(pair.Item1, pair.Item2, pair.Item3);
            }

            sw.Stop();
            DynamoCommands.WriteToLogCmd.Execute(string.Format("{0} ellapsed for loading definitions.", sw.Elapsed));

            // update search view
            searchViewModel.SearchAndUpdateResultsSync(searchViewModel.SearchText);
        }
Exemplo n.º 18
0
        private void Init()
        {
            AppDomain.CurrentDomain.AssemblyResolve += AssemblyHelper.ResolveAssembly;

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

            Model = DynamoModel.Start(
                new DynamoModel.StartConfiguration()
                {
                    StartInTestMode = true,
                    DynamoCorePath = corePath
                });

            ViewModel = DynamoViewModel.Start(
                new DynamoViewModel.StartConfiguration()
                {
                    DynamoModel = Model
                });

            //create the view
            View = new DynamoView(ViewModel);
            View.Show();                             

            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

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

            if (!Directory.Exists(TempFolder))
            {
                Directory.CreateDirectory(TempFolder);
            }
            else
            {
                EmptyTempFolder(TempFolder);
            }
        }
Exemplo n.º 19
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");

            Model = DynamoModel.Start(
                new DynamoModel.StartConfiguration()
                {
                    StartInTestMode = true
                });

            ViewModel = DynamoViewModel.Start(
                new DynamoViewModel.StartConfiguration()
                {
                    DynamoModel = Model
                });

            //create the view
            View = new DynamoView(ViewModel);
            View.Show();

            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
        }
Exemplo n.º 20
0
 /// <summary>
 /// Executes after Dynamo closes.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void dynamoView_Closed(object sender, EventArgs e)
 {
     dynamoView = null;
     isRunning = false;
 }
Exemplo n.º 21
0
        public Result Execute(ExternalCommandData revit, ref string message, ElementSet elements)
        {
            AppDomain.CurrentDomain.AssemblyResolve += 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
            {
                #region default level

                var fecLevel = new FilteredElementCollector(revit.Application.ActiveUIDocument.Document);
                fecLevel.OfClass(typeof(Level));
                var defaultLevel = fecLevel.ToElements()[0] as Level;

                #endregion

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

                DocumentManager.OnLogError += dynSettings.Controller.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";

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

                        var logger = new DynamoLogger();
                        var updateManager = new UpdateManager.UpdateManager(logger);
                        dynamoController = new DynamoController_Revit(Updater, context, updateManager,logger);

                        // Generate a view model to be the data context for the view
                        dynamoController.DynamoViewModel = new DynamoRevitViewModel(dynamoController, null);
                        dynamoController.DynamoViewModel.RequestAuthentication += ((DynamoController_Revit)dynamoController).RegisterSingleSignOn;
                        dynamoController.DynamoViewModel.CurrentSpaceViewModel.CanFindNodesFromElements = true;
                        dynamoController.DynamoViewModel.CurrentSpaceViewModel.FindNodesFromElements = ((DynamoController_Revit)dynamoController).FindNodesFromSelection;
                        
                        // Register the view model to handle sign-on requests
                        dynSettings.Controller.DynamoViewModel.RequestAuthentication += ((DynamoController_Revit)dynamoController).RegisterSingleSignOn;

                        dynamoController.VisualizationManager = new VisualizationManagerRevit();
                        
                        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.Closing += dynamoView_Closing;
                        dynamoView.Closed += dynamoView_Closed;

                        revit.Application.ViewActivating += Application_ViewActivating;
                    });
            }
            catch (Exception ex)
            {
                isRunning = false;
                MessageBox.Show(ex.ToString());

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

                return Result.Failed;
            }

            return Result.Succeeded;
        }
Exemplo n.º 22
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());
        }
Exemplo n.º 23
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;
        }
		override protected void ButtonDefinition_OnExecute(NameValueMap context)
		{
			try
			{
                if (isRunning == false)
                {
                    //Start Dynamo!  
                    DynamoInventor.SetupDynamoPaths();
                    string inventorContext = "Inventor " + PersistenceManager.InventorApplication.SoftwareVersion.DisplayVersion;

                    //Setup base units.  Need to double check what to do.  The ui default for me is inches, but API always must take cm.
                    BaseUnit.AreaUnit = AreaUnit.SquareCentimeter;
                    BaseUnit.LengthUnit = LengthUnit.Centimeter;
                    BaseUnit.VolumeUnit = VolumeUnit.CubicCentimeter;

                    //Setup DocumentManager...this is all taken care of on its own.  Reference to active application will happen
                    //when first call to binder.InventorApplication happens

                    InventorDynamoModel inventorDynamoModel = InventorDynamoModel.Start();

                    DynamoViewModel dynamoViewModel = DynamoViewModel.Start(
                    new DynamoViewModel.StartConfiguration()
                    {
                        DynamoModel = inventorDynamoModel
                    });


                    IntPtr mwHandle = Process.GetCurrentProcess().MainWindowHandle;
                    var dynamoView = new DynamoView(dynamoViewModel);
                    new WindowInteropHelper(dynamoView).Owner = mwHandle;

                    handledCrash = false;
                    dynamoView.Show();
                    isRunning = true;
                }

                else if (isRunning == true)
                {
                    System.Windows.Forms.MessageBox.Show("Dynamo is already running.");
                }

                else
                {
                    System.Windows.Forms.MessageBox.Show("Something terrible happened.");
                }		
			}

			catch(Exception e)
			{
                System.Windows.Forms.MessageBox.Show(e.ToString());
			}
		}
Exemplo n.º 25
0
        private static DynamoView InitializeCoreView()
        {
            IntPtr mwHandle = Process.GetCurrentProcess().MainWindowHandle;
            var dynamoView = new DynamoView(dynamoViewModel);
            new WindowInteropHelper(dynamoView).Owner = mwHandle;

            handledCrash = false;

            dynamoView.Dispatcher.UnhandledException += Dispatcher_UnhandledException;
            dynamoView.Closing += DynamoView_Closing;
            dynamoView.Closed += DynamoView_Closed;

            SingleSignOnManager.UIDispatcher = dynamoView.Dispatcher;

            return dynamoView;
        }
Exemplo n.º 26
0
        private void RestartTestSetup()
        {
            // Shutdown Dynamo and restart it
            View.Close();
            View = null;

            if (ViewModel != null)
            {
                ViewModel.Model.ShutDown(false);
                ViewModel = null;
            }

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

            Model = DynamoModel.Start(
                new DynamoModel.StartConfiguration()
                {
                    StartInTestMode = true
                });

            ViewModel = DynamoViewModel.Start(
                new DynamoViewModel.StartConfiguration()
                {
                    DynamoModel = Model
                });

            //create the view
            View = new DynamoView(ViewModel);
            View.Show();

            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
        }
Exemplo n.º 27
0
        private static void MakeStandaloneAndRun(string commandFilePath, out DynamoViewModel viewModel)
        {
            var geometryFactoryPath = string.Empty;
            var preloaderLocation = string.Empty;
            PreloadShapeManager(ref geometryFactoryPath, ref preloaderLocation);

            DynamoModel.RequestMigrationStatusDialog += MigrationStatusDialogRequested;

            var umConfig = UpdateManagerConfiguration.GetSettings(new SandboxLookUp());
            Debug.Assert(umConfig.DynamoLookUp != null);

            var model = DynamoModel.Start(
                new DynamoModel.DefaultStartConfiguration()
                {
                    PathResolver = new PathResolver(preloaderLocation),
                    GeometryFactoryPath = geometryFactoryPath,
                    UpdateManager = new UpdateManager(umConfig)
                });

            viewModel = DynamoViewModel.Start(
                new DynamoViewModel.StartConfiguration()
                {
                    CommandFilePath = commandFilePath,
                    DynamoModel = model
                });

            var view = new DynamoView(viewModel);
            view.Loaded += (sender, args) => CloseMigrationWindow();

            var app = new Application();
            app.Run(view);

            DynamoModel.RequestMigrationStatusDialog -= MigrationStatusDialogRequested;
        }
Exemplo n.º 28
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;
        }
Exemplo n.º 29
0
        private void RestartTestSetup(bool startInTestMode)
        {
            // Shutdown Dynamo and restart it
            View.Close();
            View = null;

            if (ViewModel != null)
            {
                var shutdownParams = new DynamoViewModel.ShutdownParams(
                    shutdownHost: false, allowCancellation: false);

                ViewModel.PerformShutdownSequence(shutdownParams);
                ViewModel = null;
            }

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

            Model = DynamoModel.Start(
                new DynamoModel.DefaultStartConfiguration()
                {
                    StartInTestMode = startInTestMode
                });

            ViewModel = DynamoViewModel.Start(
                new DynamoViewModel.StartConfiguration()
                {
                    DynamoModel = Model
                });

            //create the view
            View = new DynamoView(ViewModel);
            View.Show();

            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
        }
Exemplo n.º 30
0
        // We should load main window after Popup has been initialized.
        // If we try to load it before, we will get null.
        private void LoadMainDynamoWindow(object sender, RoutedEventArgs e)
        {
            mainDynamoWindow = WpfUtilities.FindUpVisualTree<DynamoView>(this);
            if (mainDynamoWindow == null)
                return;

            // When Dynamo window goes behind another app, the tool-tip should be hidden right 
            // away. We cannot use CloseLibraryToolTipPopup because it only hides the tool-tip 
            // window after a pause.
            mainDynamoWindow.Deactivated += (Sender, args) =>
            {
                this.DataContext = null;
                IsOpen = false;
                toolTipTimer.Stop();
            };
        }
        protected override void StartDynamo(TestSessionConfiguration testConfig)
        {
            var preloader = new Preloader(testConfig.DynamoCorePath, testConfig.RequestedLibraryVersion);
            preloader.Preload();

            var preloadedLibraries = new List<string>();
            GetLibrariesToPreload(preloadedLibraries);

            if (preloadedLibraries.Any())
            {
                if (pathResolver == null)
                    pathResolver = new TestPathResolver();

                var pr = pathResolver as TestPathResolver;
                foreach (var preloadedLibrary in preloadedLibraries.Distinct())
                {
                    pr.AddPreloadLibraryPath(preloadedLibrary);
                }
            }

            Model = DynamoModel.Start(
                new DynamoModel.DefaultStartConfiguration()
                {
                    StartInTestMode = true,
                    PathResolver = pathResolver,
                    GeometryFactoryPath = preloader.GeometryFactoryPath,
                    UpdateManager = this.UpdateManager,
                    ProcessMode = Dynamo.Core.Threading.TaskProcessMode.Synchronous
                });

            ViewModel = DynamoViewModel.Start(
                new DynamoViewModel.StartConfiguration()
                {
                    DynamoModel = Model,
                    Watch3DViewModel = HelixWatch3DViewModel.TryCreateHelixWatch3DViewModel(new Watch3DViewModelStartupParams(Model), Model.Logger)
                });

            //create the view
            View = new DynamoView(ViewModel);
            View.Show();

            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
        }
Exemplo n.º 32
0
        /// <summary>
        /// Executes after Dynamo closes.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dynamoView_Closed(object sender, EventArgs e)
        {
            var view = (DynamoView)sender;

            dynamoView = null;
            isRunning = false;

            Updater.Dispose();
            DocumentManager.OnLogError -= dynSettings.Controller.DynamoLogger.Log;

            view.Dispatcher.UnhandledException -= DispatcherOnUnhandledException;
            view.Closing -= dynamoView_Closing;
            view.Closed -= dynamoView_Closed;
            DocumentManager.Instance.CurrentUIApplication.ViewActivating -= Application_ViewActivating;

            AppDomain.CurrentDomain.AssemblyResolve -= AssemblyHelper.CurrentDomain_AssemblyResolve;
            AppDomain.CurrentDomain.AssemblyResolve -= DynamoRaaS.AssemblyHelper.ResolveAssemblies;
        }