Example #1
0
        void OnIdle(object sender, IdlingEventArgs args)
        {
            // 1. Do Rhino pending OnIdle tasks
            if (rhinoCore.OnIdle())
            {
                args.SetRaiseWithoutDelay();
                return;
            }

            // Load this assembly as a Grasshopper assembly
            if (!LoadedAsGHA && PlugIn.GetPlugInInfo(new Guid(0xB45A29B1, 0x4343, 0x4035, 0x98, 0x9E, 0x04, 0x4E, 0x85, 0x80, 0xD9, 0xCF)).IsLoaded)
            {
                LoadedAsGHA = LoadGrasshopperComponents();
            }

            // Document dependant tasks need a document
            ActiveUIApplication = (sender as UIApplication);
            if (ActiveDBDocument != null)
            {
                // 1. Do all document read actions
                if (ProcessReadActions())
                {
                    args.SetRaiseWithoutDelay();
                    return;
                }

                // 2. Do all document write actions
                if (!ActiveDBDocument.IsReadOnly)
                {
                    ProcessWriteActions();
                }

                // 3. Refresh Active View if necesary
                bool regenComplete = DirectContext3DServer.RegenComplete();
                if (pendingRefreshActiveView || !regenComplete || GH.PreviewServer.PreviewChanged())
                {
                    pendingRefreshActiveView = false;

                    var RefreshTime = new Stopwatch();
                    RefreshTime.Start();
                    ActiveUIApplication.ActiveUIDocument.RefreshActiveView();
                    RefreshTime.Stop();
                    DirectContext3DServer.RegenThreshold = Math.Min(RefreshTime.ElapsedMilliseconds, 200);
                }

                if (!regenComplete)
                {
                    args.SetRaiseWithoutDelay();
                }
            }
        }
Example #2
0
        /// <summary>
        ///   Idling Handler
        /// </summary>
        /// <remarks>
        ///   It reaches out to the analyzer and ask it to update
        ///   the results in Revit if more data has been calculated
        ///   since the last time we asked.
        ///   <para>
        ///   If there is no more data available, we unsubscribe
        ///   from the Idling event, for we do not need it anymore.
        ///   </para>
        /// </remarks>
        ///
        public void IdlingHandler(object sender, IdlingEventArgs args)
        {
            bool processing = false;

            if (m_analyzer != null)
            {
                UIApplication uiapp = sender as UIApplication;
                if (uiapp.ActiveUIDocument != null)
                {
                    // In order for the analysis to appear correctly in the view
                    // we seem to need the mechanism of a transaction to be run
                    // even though the results are not really parts of the document.

                    using (Transaction trans = new Transaction(uiapp.ActiveUIDocument.Document))
                    {
                        trans.Start("bogus transaction");
                        processing = m_analyzer.UpdateResults();
                        trans.Commit();
                    }

                    // In our case, we want Revit to get back to as as soon as possible
                    args.SetRaiseWithoutDelay();
                }
            }

            // We do not need the event once the analysis is over

            if (!processing)
            {
                UnsubscribeFromIdling(sender as UIApplication);
                m_analyzer = null;
            }
        }
Example #3
0
        private void OnIdling(object sender, IdlingEventArgs e)
        {
            var uiApp = sender as UIApplication;

            Debug.Print("OnIdling: {0}", DateTime.Now.ToString("HH:mm:ss.fff"));

            // be carefull. It loads CPU
            e.SetRaiseWithoutDelay();

            if (!TaskContainer.Instance.HasTaskToPerform)
            {
                return;
            }

            try
            {
                Debug.Print("{0}: {1}", Resources.StartExecuteTask, DateTime.Now.ToString("HH:mm:ss.fff"));

                var task = TaskContainer.Instance.DequeueTask();
                task(uiApp);

                Debug.Print("{0}: {1}", Resources.EndExecuteTask, DateTime.Now.ToString("HH:mm:ss.fff"));
            }
            catch (Exception ex)
            {
                uiApp.Application.WriteJournalComment(
                    string.Format("RevitExternalService. {0}:\r\n{2}",
                                  Resources.AnErrorOccuredWhileExecutingTheOnIdlingEvent,
                                  ex.ToString()), true);

                Debug.WriteLine(ex);
            }

            //e.SetRaiseWithoutDelay();
        }
Example #4
0
        private void OnIdling(object sender, IdlingEventArgs e)
        {
            var uiApp = sender as UIApplication;

            Debug.Print("OnIdling: {0}", DateTime.Now.ToString("HH:mm:ss.fff"));

            e.SetRaiseWithoutDelay();

            if (!TaskContainer.Instance.HasTaskToPerform)
            {
                return;
            }

            try
            {
                Debug.Print("{0}:{1}", "Revit binding ... ", DateTime.Now.ToString("HH:mm:ss.fff"));

                var task = TaskContainer.Instance.DequeueTask();
                task(uiApp);
                // TaskDialog.Show("Reivt", string.Format("{0}:{1}", "Revit binding ... ", DateTime.Now.ToString("HH:mm:ss.fff")));
                Debug.Print("{0}:{1}", "Revit binding", DateTime.Now.ToString("HH:mm:ss.fff"));
            }
            catch (Exception ex)
            {
                uiApp.Application.WriteJournalComment(
                    string.Format("RevitExternalService. {0}\r\n{1}", "Error on Idling", ex.ToString()), true);
                TaskDialog.Show("Revit", string.Format("RevitExternalService. {0}\r\n{1}", "Error on Idling", ex.ToString()));
                Debug.WriteLine(ex);
            }
        }
Example #5
0
        private void OnIdling(object sender, IdlingEventArgs e)
        {
            if (serverActive)
            {
                if (uiApp == null)
                {
                    uiApp = sender as UIApplication;
                }
                e.SetRaiseWithoutDelay();

                if (!TaskContainer.Instance.HasTaskToPerform)
                {
                    return;
                }
                try
                {
                    var task = TaskContainer.Instance.DequeueTask();
                    task(uiApp);
                }
                catch (Exception ex)
                {
                    //TaskDialog.Show("Error at Idle", ex.Message);
                    if (uiApp != null)
                    {
                        uiApp.Application.WriteJournalComment("Lyrebird Error: " + ex.ToString(), true);
                    }
                }
            }
        }
Example #6
0
        private void Application_Idling(object sender, IdlingEventArgs e)
        {
            //var app = sender as Application;
            //var uiApp = new UIApplication(app);
            var uiApp = sender as UIApplication;
            var uiDoc = uiApp.ActiveUIDocument;
            var view  = uiDoc.ActiveView;
            var doc   = uiDoc.Document;

            e.SetRaiseWithoutDelay();

            if (Math.Abs(lastCursor.X - System.Windows.Forms.Cursor.Position.X) >= 1)
            {
                var curPt = GetCurrentCursorPosition(uiDoc);
                using (var t = new Transaction(doc, "TestIdling"))
                {
                    t.Start();

                    var l = Line.CreateBound(pt1, curPt);
                    if (line == null)
                    {
                        line = doc.Create.NewDetailCurve(view, l);
                    }
                    else
                    {
                        line.GeometryCurve = l;
                    }
                    t.Commit();
                }
            }
            lastCursor = System.Windows.Forms.Cursor.Position;
        }
Example #7
0
        /// <summary>
        ///   A handler for the Idling event.
        /// </summary>
        /// <remarks>
        ///   We keep the handler very simple. First we check
        ///   if we still have the dialog. If not, we unsubscribe from Idling,
        ///   for we no longer need it and it makes Revit speedier.
        ///   If we do have the dialog around, we check if it has a request ready
        ///   and process it accordingly.
        /// </remarks>
        ///
        public void IdlingHandler(object sender, IdlingEventArgs e)
        {
            if (uiApp == null)
            {
                uiApp = sender as UIApplication;
            }
            else
            {
                // fetch the request from the dialog

                RequestId request = shellViewModel.Request.Take();

                if (request != RequestId.None)
                {
                    try
                    {
                        // we take the request, if any was made,
                        // and pass it on to the request executor

                        FamilyRequestHandler.Execute(uiApp, request);
                    }
                    finally
                    {
                        // The dialog may be in its waiting state;
                        // make sure we wake it up even if we get an exception.

                        shellViewModel.WakeUp();
                    }
                }
            }

            e.SetRaiseWithoutDelay();

            return;
        }
 private static void Application_Idling(object sender, IdlingEventArgs e)
 {
     e.SetRaiseWithoutDelay();
     while (UnlockKeys.TryDequeue(out var unlockKey))
     {
         unlockKey.Dispose();
     }
 }
Example #9
0
        static void OnIdle(object sender, IdlingEventArgs args)
        {
            ActiveUIApplication = (sender as UIApplication);

            if (ProcessIdleActions())
            {
                args.SetRaiseWithoutDelay();
            }
        }
Example #10
0
        private void Application_Idling(object sender, IdlingEventArgs e)
        {
            // see if there's something for us to do.

            try
            {
                // we want frequent callbacks
                e.SetRaiseWithoutDelay();
                ActionEnum tmpAction = _action;
                _action = ActionEnum.None;

                switch (tmpAction)
                {
                case ActionEnum.ShowElement:
                    performShow();
                    break;

                case ActionEnum.Shutdown:
                    performShutdown();
                    break;

                case ActionEnum.ColorElements:
                    performColor();
                    break;

                case ActionEnum.RemoveColor:
                    removeColor(_uiDoc.ActiveGraphicalView);
                    break;

                case ActionEnum.ResetColors:
                    resetColors();
                    break;

                case ActionEnum.ShowSolid:
                    performShowSolid();
                    break;

                case ActionEnum.ShowMove:
                    performShowMove();
                    break;

                case ActionEnum.ShowRotation:
                    performShowRotate();
                    break;

                case ActionEnum.Select:
                    performSelect();
                    break;
                }
            }
            catch (Exception ex)
            {
                TaskDialog td = new TaskDialog("Error in Revit Fingerprint");
                td.MainContent     = "An unexpected error occurred.";
                td.ExpandedContent = ex.GetType().Name + ": " + ex.Message + " " + ex.StackTrace;
            }
        }
Example #11
0
        /// <summary>
        /// The idling callback for the animation.
        /// </summary>
        /// <param name="senter"></param>
        /// <param name="e"></param>
        private void IdlingResponse(object senter, IdlingEventArgs e)
        {
            // Set to reraise idling immediately (unaffected by user activity)
            e.SetRaiseWithoutDelay();

            if (timerTripped)
            {
                timerTripped = false;
                AnimateNextStep();
            }
        }
Example #12
0
        public void OnIdling(object sender, IdlingEventArgs e)
        {
            if (receiverActivated)
            {
                UIApplication uiapp = sender as UIApplication;
                Document      doc   = uiapp.ActiveUIDocument.Document;

                e.SetRaiseWithoutDelay();

                string value = RegistryKeyManager.GetRegistryKeyValue("RhinoOutgoing");
                if (!string.IsNullOrEmpty(value))
                {
                    if (value.ToLower() == "true")
                    {
                        TaskDialog dialog = new TaskDialog("Rhino Receiver");
                        dialog.MainInstruction = "Rhino Data";
                        dialog.MainContent     = "Analysis data from Rhino is being sent to Revit.";
                        dialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Visualize Analysis Results");
                        dialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Cancel");

                        TaskDialogResult result = dialog.Show();
                        if (result == TaskDialogResult.CommandLink1)
                        {
                            //AVF
                            string   tempDirectory = RegistryKeyManager.GetRegistryKeyValue("DivaTempDirectory");
                            string[] gridFiles     = Directory.GetFiles(tempDirectory, "*-AnalysisGrid.obj");
                            if (gridFiles.Length > 0)
                            {
                                List <ObjMesh> objMeshes   = new List <ObjMesh>();
                                bool           objImported = ObjImporter.ReadObjFile(gridFiles[0], out objMeshes);

                                string dataPath         = RegistryKeyManager.GetRegistryKeyValue("RhinoOutgoingPath");
                                AnalysisDataManager avf = new AnalysisDataManager(uiapp, objMeshes, dataPath);
                                if (avf.ReadResults())
                                {
                                    if (avf.CreateGeometry())
                                    {
                                        if (avf.VisualizeData())
                                        {
                                            MessageBox.Show("Result data from Rhino was successfully visualized.");
                                        }
                                    }
                                }
                            }
                        }
                        RegistryKeyManager.SetRegistryKeyValue("RhinoOutgoing", "False");
                    }
                }
            }
        }
        void OnIdling(
            object sender,
            IdlingEventArgs ea)
        {
            ++_counter;

              if( 0 == ( _counter % _message_interval ) )
              {
            Debug.Print( "{0} OnIdling called {1} times",
              DateTime.Now.ToString( "HH:mm:ss.fff" ),
              _counter );
              }

              ea.SetRaiseWithoutDelay();
        }
Example #14
0
        static void OnIdle(object sender, IdlingEventArgs args)
        {
            if (ActiveUIApplication?.IsValidObject != true)
            {
                ActiveUIApplication = (sender as UIApplication);
            }

            if (Addin.CurrentStatus > Addin.Status.Available)
            {
                if (ProcessIdleActions())
                {
                    args.SetRaiseWithoutDelay();
                }
            }
        }
Example #15
0
        public static void OnIdle(object sender, IdlingEventArgs e)
        {
            if (Queue.IsEmpty)
            {
                return;
            }

            //do work
            var application = (UIApplication)sender;

            if (application == null)
            {
                return;
            }
            if (application.ActiveUIDocument.Document == null)
            {
                return;
            }
            Task task = null;

            try
            {
                application.Application.WriteJournalComment(
                    "Main thread id :" + Thread.CurrentThread.ManagedThreadId, false);

                task = new Task(() =>
                {
                    RevitContext.BindToken(_cts.Token);
                    RevitContext.UIApplication = application;
                    application.Application.WriteJournalComment(
                        "worker thread id :" + Thread.CurrentThread.ManagedThreadId, false);
                    Interlocked.Exchange(ref _working, 1);                     //working
                    string worker;
                    if (!Queue.TryDequeue(out worker))
                    {
                        return;
                    }
                    if (String.IsNullOrEmpty(worker))
                    {
                        return;
                    }

                    var workerType = Type.GetType(worker);
                    if (workerType == null)
                    {
                        return;
                    }
                    var workerObject = (IWorker)Activator.CreateInstance(workerType);
                    workerObject.DoWork();
                }, _cts.Token);
                task.RunSynchronously(TaskScheduler.Current);
                task.Wait(_cts.Token);
            }
            catch (OperationCanceledException ex)
            {
                // YES we cancelled
            }
            catch (AggregateException age)
            {
            }
            catch (Exception ex)
            {
                // something else happened
            }
            finally
            {
                var isCancelled = _cts.IsCancellationRequested;
                _cts = new CancellationTokenSource();
                if (task != null)
                {
                    switch (task.Status)
                    {
                    case TaskStatus.RanToCompletion:
                        RevitContext.OutputNoCancel(isCancelled
                                ? "RanToCompletion and tried to Cancel"
                                : "RanToCompletion");
                        break;

                    case TaskStatus.Faulted:
                        RevitContext.OutputNoCancel(isCancelled
                                ? "Faulted and tried to Cancel"
                                : "Faulted");
                        break;

                    case TaskStatus.Canceled:
                        RevitContext.OutputNoCancel(isCancelled
                                ? "Cancelled and tried to Cancel"
                                : "Cancelled");
                        break;
                    }
                }
                Interlocked.Exchange(ref _working, 0);
                task = null;
                // more work try idle again
                if (!Queue.IsEmpty)
                {
                    e.SetRaiseWithoutDelay();
                }
            }
        }
Example #16
0
    /// <summary>
    /// Wait far a moment before requerying database.
    /// </summary>
    //static Stopwatch _stopwatch = null;

    void OnIdling(
      object sender,
      IdlingEventArgs ea )
    {
      using( JtTimer pt = new JtTimer( "OnIdling" ) )
      {
        // Use with care! This loads the CPU:

        ea.SetRaiseWithoutDelay();

        ++_counter;

        if( 0 == ( _counter % _update_interval ) )
        {
          if( 0 == ( _counter % _message_interval ) )
          {
            Util.Log( string.Format(
              "OnIdling called {0} times",
              _counter ) );
          }

          // Have we waited long enough since the last attempt?

          //if( null == _stopwatch
          //  || _stopwatch.ElapsedMilliseconds > 500 )

          RoomEditorDb rdb = new RoomEditorDb();
          //int n = rdb.LastSequenceNumber;

          if( rdb.LastSequenceNumberChanged(
            DbUpdater.LastSequence ) )
          {
            UIApplication uiapp = sender as UIApplication;
            Document doc = uiapp.ActiveUIDocument.Document;

            Util.Log( "furniture update begin" );

            //FilteredElementCollector rooms
            //  = new FilteredElementCollector( doc )
            //    .OfClass( typeof( SpatialElement ) )
            //    .OfCategory( BuiltInCategory.OST_Rooms );

            //IEnumerable<string> roomUniqueIds
            //  = rooms.Select<Element, string>(
            //    e => e.UniqueId );

            //CouchDatabase db = rdb.Db;

            //ChangeOptions opt = new ChangeOptions();

            //opt.IncludeDocs = true;
            //opt.Since = CmdUpdate.LastSequence;
            //opt.View = "roomedit/map_room_to_furniture";

            //CouchChanges<DbFurniture> changes
            //  = db.GetChanges<DbFurniture>( opt );

            //CouchChangeResult<DbFurniture>[] results
            //  = changes.Results;

            //DbUpdater updater = new DbUpdater(
            //  doc, roomUniqueIds );

            //foreach( CouchChangeResult<DbFurniture> result
            //  in results )
            //{
            //  updater.UpdateBimFurniture( result.Doc );

            //  CmdUpdate.LastSequence = result.Sequence;
            //}

            DbUpdater updater = new DbUpdater( uiapp );

            updater.UpdateBim();

            Util.Log( "furniture update end" );

            //  _stopwatch = new Stopwatch();
            //  _stopwatch.Start();
            //}
            //catch( Exception ex )
            //{
            //  //uiapp.Application.WriteJournalComment

            //  Debug.Print(
            //    "Room Editor: an error occurred "
            //    + "executing the OnIdling event:\r\n"
            //    + ex.ToString() );

            //  Debug.WriteLine( ex );
            //}
          }
        }
      }
    }
Example #17
0
        /// <summary>
        /// The event while the app is idling (checks what is selected)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public void UIAppEvent_IdlingEventHandler(object sender, IdlingEventArgs args)
        {
            try
            {
                args.SetRaiseWithoutDelay();

                // If a thread has halted the idling handler, this if statement will
                // make sure that the process does not pass through any further.
                if (this.haltIdlingHandler)
                {
                    return;
                }

                // Initializer for everything the form needs within the Revit API context
                FirstStartup_IdlingHandler();

                Request request = GetNextRequest_IdlingHandler();

                HandleRequest_IdlingHandler(request);

                #region Stow

                /*
                 * if (!this.haltIdlingHandler)
                 * {
                 *  // This is to get the essential objects to use the Revit API
                 *  UIApplication uiApp = sender as UIApplication;
                 *  UIDocument uiDoc = uiApp.ActiveUIDocument;
                 *  Document activeDoc = uiDoc.Document;
                 *
                 *  if (this.firstStartup)
                 *  {
                 *      this.firstStartup = false;
                 *
                 *      List<ElementId> AllElementIds = revitController.GetAllElementIds(FilterMode.Project);
                 *      dataController.SetAllElements(AllElementIds);
                 *  }
                 *
                 *  Request request;
                 *  FilterMode filter;
                 *
                 *  filter = requestHandler.FilterBy;
                 *
                 *  int viewChanged = revitController.UpdateView();
                 *  if (viewChanged == 1)
                 *  {
                 *      request = Request.UpdateTreeView;
                 *  }
                 *  else
                 *  {
                 *      request = requestHandler.GetRequest();
                 *  }
                 *
                 *  request = requestHandler.ProcessRequest(request);
                 *
                 *  switch (request)
                 *  {
                 *      case Request.UpdateTreeView:
                 *
                 *          dataController.SetMode(filter);
                 *
                 *          // Update the treeView element within the form
                 *          this.BeginInvoke(new Action(() =>
                 *          {
                 *              selectionController.UpdateTreeViewStructure(dataController.AllElements, dataController.ElementTree);
                 *              // selectionController.UpdateTreeViewStructure_New(dataController.ElementTree.SubSet, dataController.ElementTree);
                 *          }));
                 *
                 *          break;
                 *      case Request.UpdateTreeViewSelection:
                 *
                 *          ICollection<ElementId> currentSelected = this.uiDoc.Selection.GetElementIds();
                 *          this.BeginInvoke(new Action(() =>
                 *          {
                 *              bool updateSucceeded = selectionController.UpdateSelectedLeaves(currentSelected);
                 *              if (updateSucceeded)
                 *              {
                 *                  requestHandler.FailureListRemove(request);
                 *              }
                 *              else
                 *              {
                 *                  requestHandler.AttemptRecovery(request);
                 *              }
                 *          }));
                 *
                 *          break;
                 *      case Request.SelectElementIds:
                 *
                 *          revitController.MakeNewSelection(dataController.SelElements);
                 *
                 *          //List<ElementId> elementIds
                 *          //    = revitController.GetAllElementIds(filter);
                 *          //dataController.UpdateAllElements(elementIds);
                 *
                 *          dataController.SetMode(filter);
                 *
                 *          // Hide all elements
                 *          if (requestHandler.UnselectedHidden)
                 *          {
                 *              revitController.HideUnselectedElementIds(
                 *                  dataController.SelElements,
                 *                  dataController.AllElements);
                 *          }
                 *          else
                 *          {
                 *              revitController.ShowSelectedElementIds(dataController.SelElements);
                 *          }
                 *
                 *          break;
                 *      case Request.ShiftSelected:
                 *
                 *          List<ElementId> movElementIds = dataController.MovElements;
                 *          List<int> coords = dataController.Coords;
                 *          bool copyAndShift = dataController.CopyAndShift;
                 *
                 *          // Copy and Move the Elements
                 *          revitController.CopyAndMoveElements(movElementIds, coords, copyAndShift);
                 *
                 *          break;
                 *      case Request.Nothing:
                 *          // Do absolutely nothing
                 *          break;
                 *      default:
                 *
                 *          // If the request isn't any other request (even Nothing), then prompt user with warning message
                 *          TaskDialog.Show("Debug - SelectionChanged_UIAppEvent_WhileIdling",
                 *              "Warning: Handler given invalid request");
                 *
                 *          break;
                 *  }
                 * }
                 */
                #endregion STOW
            }
            catch (Exception ex)
            {
                ErrorReport.Report(ex);
            }
        }
        public void OnIdle(object sender, IdlingEventArgs args)
        {
            // 1. Do Rhino pending OnIdle tasks
            if (_rhinoCore.OnIdle())
            {
                args.SetRaiseWithoutDelay();
                return;
            }

            // Document dependant tasks need a document
            var doc = (sender as UIApplication)?.ActiveUIDocument?.Document;

            if (doc == null)
            {
                return;
            }

            // 2. Do all BakeGeometry pending tasks
            lock (_bakeQueue)
            {
                if (_bakeQueue.Count > 0)
                {
                    using (var trans = new Transaction(doc))
                    {
                        if (trans.Start("BakeGeometry") == TransactionStatus.Started)
                        {
                            var categoryId = new ElementId(BuiltInCategory.OST_GenericModel);
                            while (_bakeQueue.Count > 0)
                            {
                                var geometryList = _bakeQueue.Dequeue();
                                if (geometryList != null)
                                {
                                    var ds = DirectShape.CreateElement(doc, categoryId);
                                    ds.SetShape(geometryList);
                                }
                            }
                        }

                        trans.Commit();
                    }
                }
            }

            // 3. Do all document actions
            lock (_documentActions)
            {
                if (_documentActions.Count > 0)
                {
                    using (var trans = new Transaction(doc))
                    {
                        var a    = _documentActions.Peek();
                        var name = a.GetMethodInfo().Name;
                        var s    = trans.Start(name);
                        if (s == TransactionStatus.Started)
                        {
                            try
                            {
                                _documentActions.Dequeue().Invoke(doc);
                                trans.Commit();
                            }
                            catch (Exception e)
                            {
                                Debug.Fail(e.Source, e.Message);
                                trans.RollBack();
                            }
                        }
                    }
                }

                if (_documentActions.Count > 0)
                {
                    args.SetRaiseWithoutDelay();
                }
            }
        }
Example #19
0
        /// <summary>
        /// Wait far a moment before requerying database.
        /// </summary>
        //static Stopwatch _stopwatch = null;

        void OnIdling(
            object sender,
            IdlingEventArgs ea)
        {
            using (JtTimer pt = new JtTimer("OnIdling"))
            {
                // Use with care! This loads the CPU:

                ea.SetRaiseWithoutDelay();

                ++_counter;

                if (0 == (_counter % _update_interval))
                {
                    if (0 == (_counter % _message_interval))
                    {
                        Util.Log(string.Format(
                                     "OnIdling called {0} times",
                                     _counter));
                    }

                    // Have we waited long enough since the last attempt?

                    //if( null == _stopwatch
                    //  || _stopwatch.ElapsedMilliseconds > 500 )

                    RoomEditorDb rdb = new RoomEditorDb();
                    //int n = rdb.LastSequenceNumber;

                    if (rdb.LastSequenceNumberChanged(
                            DbUpdater.LastSequence))
                    {
                        UIApplication uiapp = sender as UIApplication;
                        Document      doc   = uiapp.ActiveUIDocument.Document;

                        Util.Log("furniture update begin");

                        //FilteredElementCollector rooms
                        //  = new FilteredElementCollector( doc )
                        //    .OfClass( typeof( SpatialElement ) )
                        //    .OfCategory( BuiltInCategory.OST_Rooms );

                        //IEnumerable<string> roomUniqueIds
                        //  = rooms.Select<Element, string>(
                        //    e => e.UniqueId );

                        //CouchDatabase db = rdb.Db;

                        //ChangeOptions opt = new ChangeOptions();

                        //opt.IncludeDocs = true;
                        //opt.Since = CmdUpdate.LastSequence;
                        //opt.View = "roomedit/map_room_to_furniture";

                        //CouchChanges<DbFurniture> changes
                        //  = db.GetChanges<DbFurniture>( opt );

                        //CouchChangeResult<DbFurniture>[] results
                        //  = changes.Results;

                        //DbUpdater updater = new DbUpdater(
                        //  doc, roomUniqueIds );

                        //foreach( CouchChangeResult<DbFurniture> result
                        //  in results )
                        //{
                        //  updater.UpdateBimFurniture( result.Doc );

                        //  CmdUpdate.LastSequence = result.Sequence;
                        //}

                        DbUpdater updater = new DbUpdater(uiapp);

                        updater.UpdateBim();

                        Util.Log("furniture update end");

                        //  _stopwatch = new Stopwatch();
                        //  _stopwatch.Start();
                        //}
                        //catch( Exception ex )
                        //{
                        //  //uiapp.Application.WriteJournalComment

                        //  Debug.Print(
                        //    "Room Editor: an error occurred "
                        //    + "executing the OnIdling event:\r\n"
                        //    + ex.ToString() );

                        //  Debug.WriteLine( ex );
                        //}
                    }
                }
            }
        }
Example #20
0
        public static void OnIdle(object sender, IdlingEventArgs e)
        {
            if (Queue.IsEmpty) return;

            //do work
            var application = (UIApplication)sender;
            if (application == null) return;
            if (application.ActiveUIDocument.Document == null) return;
            Task task = null;
            try
            {
                application.Application.WriteJournalComment(
                    "Main thread id :" + Thread.CurrentThread.ManagedThreadId, false);

                task = new Task(() =>
                                    {
                                        RevitContext.BindToken(_cts.Token);
                                        RevitContext.UIApplication = application;
                                        application.Application.WriteJournalComment(
                                            "worker thread id :" + Thread.CurrentThread.ManagedThreadId, false);
                                        Interlocked.Exchange(ref _working, 1); //working
                                        string worker;
                                        if (!Queue.TryDequeue(out worker)) return;
                                        if (String.IsNullOrEmpty(worker)) return;

                                        var workerType = Type.GetType(worker);
                                        if (workerType == null) return;
                                        var workerObject = (IWorker)Activator.CreateInstance(workerType);
                                        workerObject.DoWork();
                                    },_cts.Token);
                task.RunSynchronously(TaskScheduler.Current);
                task.Wait(_cts.Token);
            }
            catch (OperationCanceledException ex)
            {
                // YES we cancelled
            }
            catch (AggregateException age)
            {

            }
            catch (Exception ex)
            {
                // something else happened
            }
            finally
            {
                var isCancelled = _cts.IsCancellationRequested;
                _cts = new CancellationTokenSource();
                if (task != null)
                    switch (task.Status)
                    {
                        case TaskStatus.RanToCompletion:
                            RevitContext.OutputNoCancel(isCancelled
                                ? "RanToCompletion and tried to Cancel"
                                : "RanToCompletion");
                            break;

                        case TaskStatus.Faulted:
                            RevitContext.OutputNoCancel(isCancelled
                                ? "Faulted and tried to Cancel"
                                : "Faulted");
                            break;

                        case TaskStatus.Canceled:
                            RevitContext.OutputNoCancel(isCancelled
                                ? "Cancelled and tried to Cancel"
                                : "Cancelled");
                            break;
                    }
                Interlocked.Exchange(ref _working, 0);
                task = null;
                // more work try idle again
                if (!Queue.IsEmpty) e.SetRaiseWithoutDelay();
            }
        }
Example #21
0
        private void OnIdling(object sender, IdlingEventArgs e)
        {
            if (serverActive)
            {
                if (uiApp == null)
                {
                    uiApp = sender as UIApplication;
                }
                e.SetRaiseWithoutDelay();

                if (!TaskContainer.Instance.HasTaskToPerform)
                {
                    return;
                }
                try
                {
                    var task = TaskContainer.Instance.DequeueTask();
                    task(uiApp);
                }
                catch (Exception ex)
                {
                    //TaskDialog.Show("Error at Idle", ex.Message);
                    if (uiApp != null) uiApp.Application.WriteJournalComment("Lyrebird Error: " + ex.ToString(), true);
                }
            }
        }
Example #22
0
        public void OnIdle(object sender, IdlingEventArgs args)
        {
            // 1. Do Rhino pending OnIdle tasks
            if (rhinoCore.OnIdle())
            {
                args.SetRaiseWithoutDelay();
                return;
            }

            // Load this assembly as a Grasshopper assembly
            if (!LoadedAsGHA && PlugIn.GetPlugInInfo(new Guid(0xB45A29B1, 0x4343, 0x4035, 0x98, 0x9E, 0x04, 0x4E, 0x85, 0x80, 0xD9, 0xCF)).IsLoaded)
            {
                LoadedAsGHA = LoadGrasshopperComponents();
            }

            // Document dependant tasks need a document
            ActiveUIApplication = (sender as UIApplication);
            if (ActiveDBDocument != null)
            {
                // 2. Do all BakeGeometry pending tasks
                lock (bakeRecipeQueue)
                {
                    if (bakeRecipeQueue.Count > 0)
                    {
                        using (var trans = new Transaction(ActiveDBDocument))
                        {
                            if (trans.Start("BakeGeometry") == TransactionStatus.Started)
                            {
                                while (bakeRecipeQueue.Count > 0)
                                {
                                    var recipe = bakeRecipeQueue.Dequeue();

                                    if (recipe.geometryToBake != null && recipe.categoryToBakeInto != BuiltInCategory.INVALID)
                                    {
                                        try
                                        {
                                            var geometryList = new List <GeometryObject>();

                                            // DirectShape only accepts those types and no nulls
                                            foreach (var g in recipe.geometryToBake)
                                            {
                                                switch (g)
                                                {
                                                case Point p: geometryList.Add(p); break;

                                                case Curve c: geometryList.Add(c); break;

                                                case Solid s: geometryList.Add(s); break;

                                                case Mesh m: geometryList.Add(m); break;
                                                }
                                            }

                                            if (geometryList.Count > 0)
                                            {
                                                var ds = DirectShape.CreateElement(ActiveDBDocument, new ElementId(recipe.categoryToBakeInto));
                                                ds.SetShape(geometryList);
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            Debug.Fail(e.Source, e.Message);
                                        }
                                    }
                                }
                            }

                            trans.Commit();
                        }
                    }
                }

                // 3. Do all document actions
                lock (documentActions)
                {
                    if (documentActions.Count > 0)
                    {
                        using (var trans = new Transaction(ActiveDBDocument))
                        {
                            try
                            {
                                if (trans.Start("RhinoInside") == TransactionStatus.Started)
                                {
                                    while (documentActions.Count > 0)
                                    {
                                        documentActions.Dequeue().Invoke(ActiveDBDocument);
                                    }

                                    Committing = true;
                                    trans.Commit();
                                    Committing = false;

                                    foreach (GH_Document definition in Grasshopper.Instances.DocumentServer)
                                    {
                                        if (definition.Enabled)
                                        {
                                            definition.NewSolution(false);
                                        }
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                Debug.Fail(e.Source, e.Message);

                                if (trans.HasStarted())
                                {
                                    trans.RollBack();
                                }
                            }
                            finally
                            {
                                documentActions.Clear();
                            }
                        }
                    }
                }
            }
        }
Example #23
0
        /// <summary>
        /// Handle Revit Idling event.
        /// Return immediately if less time elapsed than
        /// specified interval.
        /// Otherwise, download the current image file
        /// from the specified URL.
        /// If it has not changed since the last update,
        /// return immediately.
        /// Otherwise, update the spatial field primitive
        /// with the new image data.
        /// Currently, we only display a grey scale image.
        /// Colour images could be handled as well by
        /// defining a custom colour palette.
        /// </summary>
        static void OnIdling(
            object sender,
            IdlingEventArgs e)
        {
            if (_raise_without_delay)
            {
                e.SetRaiseWithoutDelay();
            }

            if (DateTime.Now.Subtract(_lastUpdate)
                > _interval)
            {
                Log("OnIdling");

                GreyscaleBitmapData data
                    = new GreyscaleBitmapData(
                          _width, _height, _url);

                byte[] hash = data.HashValue;

                if (null == _lastHash ||
                    0 != CompareBytes(hash, _lastHash))
                {
                    _lastHash = hash;

                    // Access active document from sender:

                    // Support both 2011, where sender is an
                    // Application instance, and 2012, where
                    // it is a UIApplication instance:

                    UIApplication uiapp
                        = sender is UIApplication
            ? sender as UIApplication                 // 2012
            : new UIApplication(
                              sender as Application); // 2011

                    Debug.Assert(null != uiapp,
                                 "expected a valid Revit UIApplication instance");

                    UIDocument uidoc = uiapp.ActiveUIDocument;
                    Document   doc   = uidoc.Document;

                    Log("OnIdling image changed, active document "
                        + doc.Title);

                    Transaction transaction
                        = new Transaction(doc, "Revit Webcam Update");

                    transaction.Start();

                    View view = doc.ActiveView; // maybe has to be 3D

                    SpatialFieldManager sfm
                        = SpatialFieldManager.GetSpatialFieldManager(
                              view);

                    if (null == sfm)
                    {
                        sfm = SpatialFieldManager
                              .CreateSpatialFieldManager(view, 1);
                    }

                    if (0 > _sfp_index)
                    {
                        _sfp_index = sfm.AddSpatialFieldPrimitive(
                            _faceReference);
                    }

                    int nPoints = data.Width * data.Height;

                    IList <UV> pts = new List <UV>(nPoints);

                    IList <ValueAtPoint> valuesAtPoints
                        = new List <ValueAtPoint>(nPoints);

                    // warning CS0618:
                    // GeometryObject is obsolete: Property will be removed.
                    // Use Element.GetGeometryObjectFromReference(Reference) instead

                    //Face face = _faceReference.GeometryObject as Face; // 2011

                    //Face face = doc.get_Element( _elementId )
                    //  .GetGeometryObjectFromReference(
                    //    _faceReference ) as Face; // 2012

                    // warning CS0618:
                    // Autodesk.Revit.DB.Document.get_Element(Autodesk.Revit.DB.ElementId) is obsolete:
                    // This method has been obsoleted. Use GetElement() instead.

                    //Element eFace = doc.get_Element( _elementId ); // 2012

                    Element eFace = doc.GetElement(_elementId); // 2013

                    Face face = eFace.GetGeometryObjectFromReference(
                        _faceReference) as Face; // 2012

                    GetFieldPointsAndValues(ref pts,
                                            ref valuesAtPoints, ref data, face);

                    FieldDomainPointsByUV fieldPoints
                        = new FieldDomainPointsByUV(pts);

                    FieldValues fieldValues
                        = new FieldValues(valuesAtPoints);

                    int         result_index;
                    IList <int> registeredResults = sfm.GetRegisteredResults();
                    if (0 == registeredResults.Count)
                    {
                        AnalysisResultSchema resultSchema
                            = new AnalysisResultSchema(
                                  "Schema 1", "Schema 1 Description");

                        result_index = sfm.RegisterResult(
                            resultSchema);
                    }
                    else
                    {
                        result_index = registeredResults.First();
                    }

                    // warning CS0618:
                    // UpdateSpatialFieldPrimitive(int, FieldDomainPoints, FieldValues) is obsolete:
                    // This method is obsolete in Revit 2012; use the overload accepting the result index instead.

                    //sfm.UpdateSpatialFieldPrimitive(
                    //  _sfp_index, fieldPoints, fieldValues ); // 2011

                    sfm.UpdateSpatialFieldPrimitive(
                        _sfp_index, fieldPoints, fieldValues,
                        result_index); // 2012

                    doc.Regenerate();
                    transaction.Commit();

                    _lastUpdate = DateTime.Now;
                }
            }
        }
Example #24
0
        public void OnIdle(object sender, IdlingEventArgs args)
        {
            // 1. Do Rhino pending OnIdle tasks
            if (rhinoCore.OnIdle())
            {
                args.SetRaiseWithoutDelay();
                return;
            }

            // Document dependant tasks need a document
            var doc = (sender as UIApplication)?.ActiveUIDocument?.Document;

            if (doc == null)
            {
                return;
            }

            // 2. Do all BakeGeometry pending tasks
            lock (bakeRecipeQueue)
            {
                if (bakeRecipeQueue.Count > 0)
                {
                    using (var trans = new Transaction(doc))
                    {
                        if (trans.Start("BakeGeometry") == TransactionStatus.Started)
                        {
                            while (bakeRecipeQueue.Count > 0)
                            {
                                BakeRecipe recipe = bakeRecipeQueue.Dequeue();

                                if (recipe.geometryToBake != null && recipe.categoryToBakeInto != BuiltInCategory.INVALID)
                                {
                                    try
                                    {
                                        var geometryList = new List <GeometryObject>();

                                        // DirectShape only accepts those types and no nulls
                                        foreach (var g in recipe.geometryToBake)
                                        {
                                            switch (g)
                                            {
                                            case Point p: geometryList.Add(p); break;

                                            case Curve c: geometryList.Add(c); break;

                                            case Solid s: geometryList.Add(s); break;

                                            case Mesh m: geometryList.Add(m); break;
                                            }
                                        }

                                        if (geometryList.Count > 0)
                                        {
                                            var ds = DirectShape.CreateElement(doc, new ElementId(recipe.categoryToBakeInto));
                                            ds.SetShape(geometryList);
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        Debug.Fail(e.Source, e.Message);
                                    }
                                }
                            }
                        }

                        trans.Commit();
                    }
                }
            }

            // 3. Do all document actions
            lock (documentActions)
            {
                if (documentActions.Count > 0)
                {
                    using (var trans = new Transaction(doc))
                    {
                        var action = documentActions.Peek();
                        if (trans.Start(action.GetMethodInfo().Name) == TransactionStatus.Started)
                        {
                            try
                            {
                                documentActions.Dequeue().Invoke(doc);
                                trans.Commit();
                            }
                            catch (Exception e)
                            {
                                Debug.Fail(e.Source, e.Message);
                                trans.RollBack();
                            }
                        }
                    }
                }

                if (documentActions.Count > 0)
                {
                    args.SetRaiseWithoutDelay();
                }
            }
        }
Example #25
0
        private void OnIdling(object sender, IdlingEventArgs e)
        {
            var uiApp = sender as UIApplication;

            Debug.Print("OnIdling: {0}", DateTime.Now.ToString("HH:mm:ss.fff"));

            // be carefull. It loads CPU
            e.SetRaiseWithoutDelay();

            if (!TaskContainer.Instance.HasTaskToPerform)
                return;

            try
            {
                Debug.Print("{0}: {1}", Resources.StartExecuteTask, DateTime.Now.ToString("HH:mm:ss.fff"));

                var task = TaskContainer.Instance.DequeueTask();
                task(uiApp);

                Debug.Print("{0}: {1}", Resources.EndExecuteTask, DateTime.Now.ToString("HH:mm:ss.fff"));
            }
            catch (Exception ex)
            {
                uiApp.Application.WriteJournalComment(
                    string.Format("RevitExternalService. {0}:\r\n{2}",
                    Resources.AnErrorOccuredWhileExecutingTheOnIdlingEvent,
                    ex.ToString()), true);

                Debug.WriteLine(ex);
            }

            //e.SetRaiseWithoutDelay();
        }