Пример #1
0
 public PortData(string nickName, string tip, Type portType, FScheme.Value defaultValue=null)
 {
     NickName = nickName;
     ToolTipString = tip;
     PortType = portType;
     DefaultValue = defaultValue;
 }
Пример #2
0
        public override FScheme.Value Evaluate(FSharpList <FScheme.Value> args)
        {
            var thunk = ((FScheme.Value.Function)args[0]).Item;
            var task  = FScheme.MakeFuture(thunk);

            return(FScheme.Value.NewContainer(task));
        }
Пример #3
0
        /// <summary>
        ///     Class constructor
        /// </summary>
        public DynamoController(ExecutionEnvironment env,
                                Type viewModelType, string context, string commandFilePath)
        {
            DynamoLogger.Instance.StartLogging();

            dynSettings.Controller = this;

            this.Context = context;

            //Start heartbeat reporting
            Services.InstrumentationLogger.Start();

            //create the view model to which the main window will bind
            //the DynamoModel is created therein
            this.DynamoViewModel = (DynamoViewModel)Activator.CreateInstance(
                viewModelType, new object[] { this, commandFilePath });

            // custom node loader
            string directory   = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string pluginsPath = Path.Combine(directory, "definitions");

            CustomNodeManager = new CustomNodeManager(pluginsPath);

            SearchViewModel = new SearchViewModel();

            dynSettings.PackageLoader = new PackageLoader();

            dynSettings.PackageLoader.DoCachedPackageUninstalls();
            dynSettings.PackageLoader.LoadPackages();

            FSchemeEnvironment = env;

            DynamoViewModel.Model.CurrentWorkspace.X = 0;
            DynamoViewModel.Model.CurrentWorkspace.Y = 0;

            DynamoLogger.Instance.Log(String.Format(
                                          "Dynamo -- Build {0}",
                                          Assembly.GetExecutingAssembly().GetName().Version));

            DynamoLoader.ClearCachedAssemblies();
            DynamoLoader.LoadBuiltinTypes();

            //run tests
            if (FScheme.RunTests(DynamoLogger.Instance.Log))
            {
                DynamoLogger.Instance.Log("All Tests Passed. Core library loaded OK.");
            }

            this.InfoBubbleViewModel = new InfoBubbleViewModel();

            AddPythonBindings();
        }
Пример #4
0
        /// <summary>
        ///     Class constructor
        /// </summary>
        public DynamoController(ExecutionEnvironment env, Type viewModelType, string context)
        {
            dynSettings.Controller = this;

            this.Context = context;

            //Start heartbeat reporting
            Services.InstrumentationLogger.Start();

            //create the view model to which the main window will bind
            //the DynamoModel is created therein
            this.DynamoViewModel = (DynamoViewModel)Activator.CreateInstance(viewModelType, new object[] { this });

            // custom node loader
            string directory   = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string pluginsPath = Path.Combine(directory, "definitions");

            CustomNodeManager = new CustomNodeManager(pluginsPath);

            SearchViewModel                  = new SearchViewModel();
            PackageManagerClient             = new PackageManagerClient();
            dynSettings.PackageManagerClient = PackageManagerClient;
            PublishPackageViewModel          = new PublishPackageViewModel(PackageManagerClient);

            dynSettings.PackageLoader = new PackageLoader();

            dynSettings.PackageLoader.DoCachedPackageUninstalls();
            dynSettings.PackageLoader.LoadPackages();

            FSchemeEnvironment = env;

            DynamoViewModel.Model.CurrentSpace.X = DynamoView.CANVAS_OFFSET_X;
            DynamoViewModel.Model.CurrentSpace.Y = DynamoView.CANVAS_OFFSET_Y;

            dynSettings.Controller.DynamoViewModel.Log(String.Format(
                                                           "Dynamo -- Build {0}",
                                                           Assembly.GetExecutingAssembly().GetName().Version));

            DynamoLoader.ClearCachedAssemblies();
            DynamoLoader.LoadBuiltinTypes();

            //run tests
            if (FScheme.RunTests(dynSettings.Controller.DynamoViewModel.Log))
            {
                dynSettings.Controller.DynamoViewModel.Log("All Tests Passed. Core library loaded OK.");
            }

            NodeSubmittedForRendering += new EventHandler(Controller_NodeSubmittedForRendering);
            NodeRemovedFromRendering  += new EventHandler(Controller_NodeRemovedFromRendering);
        }
Пример #5
0
 //Returns an FScheme Expression which wraps the given ExternFunc, so that it
 //can be called by FScheme.
 public static Expression MakeFunction(FScheme.ExternFunc func)
 {
     //return Expression.NewFunction(
      //   FuncConvert.ToFSharpFunc(
      //      delegate(FSharpFunc<Expression, Expression> c)
      //      {
      //         return FuncConvert.ToFSharpFunc(
      //            delegate(FSharpList<Expression> args)
      //            {
      //               return c.Invoke(func(args));
      //            }
      //         );
      //      }
      //   )
      //);
      return FScheme.makeExternFunc(func);
 }
Пример #6
0
 internal static dynamic convertFromValue(FScheme.Value exp)
 {
     if (exp.IsList)
         return ((FScheme.Value.List)exp).Item.Select(x => convertFromValue(x)).ToList();
     else if (exp.IsNumber)
         return ((FScheme.Value.Number)exp).Item;
     else if (exp.IsString)
         return ((FScheme.Value.String)exp).Item;
     else if (exp.IsContainer)
         return ((FScheme.Value.Container)exp).Item;
     //else if (exp.IsFunction)
     //{
     //   return new Func<IList<dynamic>, dynamic>(
     //      args =>
     //         ((Value.Function)exp).Item
     //            .Invoke(ExecutionEnvironment.IDENT)
     //            .Invoke(Utils.convertSequence(args.Select(
     //               x => (Value)Converters.convertToValue(x)
     //            )))
     //   );
     //}
     //else if (exp.IsSpecial)
     //{
     //   return new Func<IList<dynamic>, dynamic>(
     //      args =>
     //         ((Value.Special)exp).Item
     //            .Invoke(ExecutionEnvironment.IDENT)
     //            .Invoke(
     //}
     //else if (exp.IsCurrent)
     //{
     //   return new Func<dynamic, dynamic>(
     //      ex =>
     //         Converters.convertFromValue(
     //            ((Value.Current)exp).Item.Invoke(Converters.convertToValue(ex))
     //         )
     //   );
     //}
     else
         throw new Exception("Not allowed to pass Functions into a Python Script.");
 }
Пример #7
0
 public static Expression MakeMacro(FScheme.ExternMacro macro)
 {
     //return Expression.NewSpecial(
      //   FuncConvert.ToFSharpFunc(
      //     delegate(FSharpFunc<Expression, Expression> c)
      //     {
      //        return FuncConvert.ToFSharpFunc(
      //           delegate(FSharpList<FSharpRef<FSharpMap<string, FSharpRef<Expression>>>> env)
      //           {
      //              return FuncConvert.ToFSharpFunc(
      //                 delegate(FSharpList<Expression> args)
      //                 {
      //                    return c.Invoke(macro(args, env));
      //                 }
      //              );
      //           }
      //        );
      //     }
      //   )
      //);
      return FScheme.makeExternMacro(macro);
 }
Пример #8
0
        internal static dynamic convertFromValue(FScheme.Value exp, ObjectOperations invoker)
        {
            if (exp.IsList)
                return ((FScheme.Value.List)exp).Item.Select(x => convertFromValue(x, invoker)).ToList();
            else if (exp.IsNumber)
                return ((FScheme.Value.Number)exp).Item;
            else if (exp.IsString)
                return ((FScheme.Value.String)exp).Item;
            else if (exp.IsContainer)
                return ((FScheme.Value.Container)exp).Item;
            else if (exp.IsFunction)
            {
                var func = ((FScheme.Value.Function)exp).Item;

                PyWrapper wrapped =
                    args =>
                        convertFromValue(
                            func.Invoke(args.Select(a => convertToValue(a, invoker) as FScheme.Value).ToFSharpList()), invoker);

                return wrapped;
            }
            else
                throw new Exception("Not allowed to pass Functions into a Python Script.");
        }
Пример #9
0
 private static FScheme.Value _setParam(FamilySymbol ft, Parameter p, FScheme.Value valueExpr)
 {
     if (p.StorageType == StorageType.Double)
     {
         p.Set(((FScheme.Value.Number)valueExpr).Item);
     }
     else if (p.StorageType == StorageType.Integer)
     {
         p.Set((int)((FScheme.Value.Number)valueExpr).Item);
     }
     else if (p.StorageType == StorageType.String)
     {
         p.Set(((FScheme.Value.String)valueExpr).Item);
     }
     else if (valueExpr.IsNumber)
     {
         p.Set(new ElementId((int)(valueExpr as FScheme.Value.Number).Item));
     }
     else
     {
         p.Set((ElementId)((FScheme.Value.Container)valueExpr).Item);
     }
     return FScheme.Value.NewContainer(ft);
 }
Пример #10
0
 public virtual bool acceptsListOfLists(FScheme.Value value)
 {
     return false;
 }
Пример #11
0
 private static FScheme.Value setParam(FamilySymbol fi, Definition paramDef, FScheme.Value valueExpr)
 {
     var p = fi.get_Parameter(paramDef);
     if (p != null)
     {
         return _setParam(fi, p, valueExpr);
     }
     throw new Exception("Parameter \"" + paramDef.Name + "\" was not found!");
 }
Пример #12
0
        public static SIUnit UnwrapToSIUnit(FScheme.Value value)
        {
            if (value.IsContainer)
            {
                var measure = ((FScheme.Value.Container)value).Item as SIUnit;
                if (measure != null)
                {
                    return measure;
                }
            }

            throw new Exception("The value was not convertible to a unit of measure.");
        }
Пример #13
0
        public override FScheme.Value Evaluate(FSharpList <FScheme.Value> args)
        {
            var task = (Task <FScheme.Value>)((FScheme.Value.Container)args[0]).Item;

            return(FScheme.Redeem(task));
        }
Пример #14
0
 public double GetDoubleFromFSchemeValue(FScheme.Value value)
 {
     var doubleWatchVal = 0.0;
     Assert.AreEqual(true, FSchemeInterop.Utils.Convert(value, ref doubleWatchVal));
     return doubleWatchVal;
 }
Пример #15
0
 public static FScheme.Value ConvertListToHostUnits(FScheme.Value.List value)
 {
     var list = value.Item;
     return FScheme.Value.NewList(FSchemeInterop.Utils.SequenceToFSharpList(list.Select(UnwrapToDoubleWithHostUnitConversion)));
 }
Пример #16
0
 /// <summary>
 /// Log an expression
 /// </summary>
 /// <param name="expression"></param>
 public void Log(FScheme.Expression expression)
 {
     Instance.Log(FScheme.printExpression("\t", expression), LogLevel.Console);
 }
Пример #17
0
        protected override bool AcceptsListOfLists(FScheme.Value value)
        {
            if (Utils.IsListOfListsOfLists(value))
                return false;

            FSharpList<FScheme.Value> vals = ((FScheme.Value.List)value).Item;
            if (!vals.Any() || !(vals[0] is FScheme.Value.List))
                return true;
            FSharpList<FScheme.Value> firstListInList = ((FScheme.Value.List)vals[0]).Item;
            if (!firstListInList.Any() || !(firstListInList[0] is FScheme.Value.Container))
                return true;
            var var1 = ((FScheme.Value.Container)firstListInList[0]).Item;
            if (var1 is ModelCurveArray)
                return false;

            return true;
        }
Пример #18
0
 /// <summary>
 /// A better ToString() for Values.
 /// </summary>
 /// <param name="v"></param>
 /// <returns></returns>
 public static string Print(this Value v)
 {
     return(v.IsString
         ? (v as Value.String).Item
         : FScheme.print(v));
 }
Пример #19
0
 /// <summary>
 /// A better ToString() for Values.
 /// </summary>
 /// <param name="v"></param>
 /// <returns></returns>
 public static string Print(this Value v)
 {
     return(FScheme.print(v));
 }
Пример #20
0
        public static void Main(string[] args)
        {
            var env = new Dynamo.FSchemeInterop.ExecutionEnvironment();

            FScheme.REPL(true);
        }
Пример #21
0
 //Binds symbols of the given string to the given Expression.
 //private void DefineExternal(string name, Expression func)
 //{
 //   this.env.Add(name, func);
 //}
 //Binds symbols of the given string to the given External Function.
 public void DefineExternal(string name, FScheme.ExternFunc func)
 {
     this.DefineSymbol(name, FuncContainer.MakeFunction(func));
 }
Пример #22
0
        protected override void Run(IEnumerable<dynNode> topElements, FScheme.Expression runningExpression)
        {
            //If we are not running in debug...
            if (!_debug)
            {
                //Do we need manual transaction control?
                bool manualTrans = topElements.Any(checkManualTransaction.TraverseUntilAny);

                //Can we avoid running everything in the Revit Idle thread?
                bool noIdleThread = manualTrans || !topElements.Any(checkRequiresTransaction.TraverseUntilAny);

                //If we don't need to be in the idle thread...
                if (noIdleThread)
                {
                    this.TransMode = TransactionMode.Manual; //Manual transaction control
                    this.InIdleThread = false; //Not in idle thread at the moment
                    base.Run(topElements, runningExpression); //Just run the Run Delegate
                }
                else //otherwise...
                {
                    this.TransMode = TransactionMode.Automatic; //Automatic transaction control
                    this.InIdleThread = true; //Now in the idle thread.
                    IdlePromise.ExecuteOnIdle(new Action(
                        () => base.Run(topElements, runningExpression)),
                        false); //Execute the Run Delegate in the Idle thread.
                }
            }
            else //If we are in debug mode...
            {
                this.TransMode = TransactionMode.Debug; //Debug transaction control
                this.InIdleThread = true; //Everything will be evaluated in the idle thread.

                Bench.Dispatcher.Invoke(new Action(
                   () => Bench.Log("Running expression in debug.")
                ));

                //Execute the Run Delegate.
                base.Run(topElements, runningExpression);
            }
        }
Пример #23
0
        /// <summary>
        /// Returns the objects from a Value type which have associated visualizers 
        /// along with a string tag representing the array index of the value, i.e. [0][5][3]
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static Dictionary<string, object> GetDrawableFromValue(List<int> chain, FScheme.Value value)
        {
            //var drawables = new List<object>();
            var drawables = new Dictionary<string, object>();

            if (value == null)
            {
                return drawables;
            }

            var viz = dynSettings.Controller.VisualizationManager;

            if (value.IsList)
            {
                int count = 0;
                foreach (var val_inner in ((FScheme.Value.List)value).Item)
                {
                    var subChain = new List<int>(chain);
                    subChain.Add(count);
                    var innerDrawables = GetDrawableFromValue(subChain, val_inner);
                    innerDrawables.ToList().ForEach(x=>drawables.Add(x.Key, x.Value));

                    count++;
                }
                return drawables;
            }

            var container = value as FScheme.Value.Container;
            if (container == null)
                return drawables;

            var obj = ((FScheme.Value.Container)container).Item;

            if (obj != null)
            {
                var t = obj.GetType();
                var visualizer = viz.Visualizers.FirstOrDefault(x => x.Key == t || x.Key.IsAssignableFrom(t));

                if (visualizer.Value != null)
                {
                    drawables.Add(TagFromList(chain),obj);
                }
            }

            return drawables;
        }
Пример #24
0
        /// <summary>
        ///     Class constructor
        /// </summary>
        public DynamoController(ExecutionEnvironment env,
                                Type viewModelType, string context, string commandFilePath, IUpdateManager updateManager, IUnitsManager units, IWatchHandler watchHandler, IPreferences preferences)
        {
            DynamoLogger.Instance.StartLogging();

            dynSettings.Controller = this;

            this.Context = context;

            //Start heartbeat reporting
            Services.InstrumentationLogger.Start();

            PreferenceSettings = preferences;
            ((PreferenceSettings)PreferenceSettings).PropertyChanged += PreferenceSettings_PropertyChanged;

            UnitsManager              = units;
            UnitsManager.LengthUnit   = PreferenceSettings.LengthUnit;
            UnitsManager.AreaUnit     = PreferenceSettings.AreaUnit;
            UnitsManager.VolumeUnit   = PreferenceSettings.VolumeUnit;
            UnitsManager.NumberFormat = PreferenceSettings.NumberFormat;

            UpdateManager = updateManager;
            UpdateManager.UpdateDownloaded  += updateManager_UpdateDownloaded;
            UpdateManager.ShutdownRequested += updateManager_ShutdownRequested;
            UpdateManager.CheckForProductUpdate(new UpdateRequest(new Uri(Configurations.UpdateDownloadLocation), DynamoLogger.Instance, UpdateManager.UpdateDataAvailable));

            WatchHandler = watchHandler;

            //create the view model to which the main window will bind
            //the DynamoModel is created therein
            this.DynamoViewModel = (DynamoViewModel)Activator.CreateInstance(
                viewModelType, new object[] { this, commandFilePath });

            // custom node loader
            string directory   = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string pluginsPath = Path.Combine(directory, "definitions");

            CustomNodeManager = new CustomNodeManager(pluginsPath);

            SearchViewModel = new SearchViewModel();

            dynSettings.PackageLoader = new PackageLoader();

            dynSettings.PackageLoader.DoCachedPackageUninstalls();
            dynSettings.PackageLoader.LoadPackages();

            FSchemeEnvironment = env;

            DynamoViewModel.Model.CurrentWorkspace.X = 0;
            DynamoViewModel.Model.CurrentWorkspace.Y = 0;

            DynamoLogger.Instance.Log(String.Format(
                                          "Dynamo -- Build {0}",
                                          Assembly.GetExecutingAssembly().GetName().Version));

            DynamoLoader.ClearCachedAssemblies();
            DynamoLoader.LoadBuiltinTypes();

            //run tests
            if (FScheme.RunTests(DynamoLogger.Instance.Log))
            {
                DynamoLogger.Instance.Log("All Tests Passed. Core library loaded OK.");
            }

            this.InfoBubbleViewModel = new InfoBubbleViewModel();

            AddPythonBindings();

            MigrationManager.Instance.MigrationTargets.Add(typeof(WorkspaceMigrations));
        }
Пример #25
0
        protected override void Run(IEnumerable<dynNodeModel> topElements, FScheme.Expression runningExpression)
        {
            //If we are not running in debug...
            if (!this.DynamoViewModel.RunInDebug)
            {
                //Do we need manual transaction control?
                bool manualTrans = topElements.Any((DynamoViewModel as DynamoRevitViewModel).CheckManualTransaction.TraverseUntilAny);

                //Can we avoid running everything in the Revit Idle thread?
                bool noIdleThread = manualTrans || !topElements.Any((DynamoViewModel as DynamoRevitViewModel).CheckRequiresTransaction.TraverseUntilAny);

                //If we don't need to be in the idle thread...
                if (noIdleThread)
                {
                    DynamoLogger.Instance.Log("Running expression in evaluation thread...");
                    (DynamoViewModel as DynamoRevitViewModel).TransMode = DynamoRevitViewModel.TransactionMode.Manual; //Manual transaction control
                    this.InIdleThread = false; //Not in idle thread at the moment
                    base.Run(topElements, runningExpression); //Just run the Run Delegate
                }
                else //otherwise...
                {
                    DynamoLogger.Instance.Log("Running expression in Revit's Idle thread...");
                    (DynamoViewModel as DynamoRevitViewModel).TransMode = DynamoRevitViewModel.TransactionMode.Automatic; //Automatic transaction control
                    this.InIdleThread = true; //Now in the idle thread.
                    IdlePromise.ExecuteOnIdle(new Action(
                        () => base.Run(topElements, runningExpression)),
                        false); //Execute the Run Delegate in the Idle thread.
                }
            }
            else //If we are in debug mode...
            {
                (DynamoViewModel as DynamoRevitViewModel).TransMode = DynamoRevitViewModel.TransactionMode.Debug; //Debug transaction control
                this.InIdleThread = true; //Everything will be evaluated in the idle thread.

                //MVVM: no need to invoke through UI
                //Bench.Dispatcher.Invoke(new Action(
                //   () => dynSettings.Controller.DynamoViewModel.Log("Running expression in debug.")
                //));

                dynSettings.Controller.DynamoViewModel.Log("Running expression in debug.");

                //Execute the Run Delegate.
                base.Run(topElements, runningExpression);
            }
        }
Пример #26
0
        protected virtual void Run(List <dynNodeModel> topElements, FScheme.Expression runningExpression)
        {
            //Print some stuff if we're in debug mode
            if (DynamoViewModel.RunInDebug)
            {
                if (dynSettings.Controller.UIDispatcher != null)
                {
                    foreach (string exp in topElements.Select(node => node.PrintExpression()))
                    {
                        DynamoLogger.Instance.Log("> " + exp);
                    }
                }
            }

            try
            {
                DynamoLogger.Instance.Log("Evaluating the expression...");

                //Evaluate the expression
                FScheme.Value expr = FSchemeEnvironment.Evaluate(runningExpression);

                if (dynSettings.Controller.UIDispatcher != null)
                {
                    //Print some more stuff if we're in debug mode
                    if (DynamoViewModel.RunInDebug && expr != null)
                    {
                        DynamoLogger.Instance.Log(FScheme.print(expr));
                    }
                }
            }
            catch (CancelEvaluationException ex)
            {
                /* Evaluation was cancelled */

                OnRunCancelled(false);
                RunCancelled = false;
                if (ex.Force)
                {
                    runAgain = false;
                }
            }
            catch (Exception ex)
            {
                /* Evaluation failed due to error */

                if (dynSettings.Controller.UIDispatcher != null)
                {
                    //Print unhandled exception
                    if (ex.Message.Length > 0)
                    {
                        dynSettings.Controller.DispatchOnUIThread(() => DynamoLogger.Instance.Log(ex));
                    }
                }

                OnRunCancelled(true);
                RunCancelled = true;
                runAgain     = false;

                //If we are testing, we need to throw an exception here
                //which will, in turn, throw an Assert.Fail in the
                //Evaluation thread.
                if (Testing)
                {
                    throw new Exception(ex.Message);
                }
            }

            OnEvaluationCompleted();
        }
Пример #27
0
 public FSharpList<FScheme.Value> GetListFromFSchemeValue(FScheme.Value value)
 {
     FSharpList<FScheme.Value> listWatchVal = null;
     Assert.AreEqual(true, FSchemeInterop.Utils.Convert(value, ref listWatchVal));
     return listWatchVal;
 }
Пример #28
0
        /// <summary>
        /// Utility method to get the Revit geometry associated with nodes.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private static List<GeometryObject> RevitGeometryFromNodes(FScheme.Value value)
        {
            var geoms = new List<GeometryObject>();

            if (value == null)
            {
                return geoms;
            }

            if (value.IsList)
            {
                foreach (var val_inner in ((FScheme.Value.List)value).Item)
                {
                    geoms.AddRange(RevitGeometryFromNodes(val_inner));
                }
                return geoms;
            }

            var container = value as Value.Container;
            if (container == null)
                return geoms;

            var geom = ((FScheme.Value.Container)value).Item as GeometryObject;
            if (geom != null && !(geom is Face))
                geoms.Add(geom);

            var ps = ((FScheme.Value.Container) value).Item as ParticleSystem;
            if (ps != null)
            {
                geoms.AddRange(ps.Springs.Select(spring => Line.CreateBound(spring.getOneEnd().getPosition(), spring.getTheOtherEnd().getPosition())).Cast<GeometryObject>());
            }

            var cl = ((FScheme.Value.Container) value).Item as Autodesk.Revit.DB.CurveLoop;
            if (cl != null)
            {
                geoms.AddRange(cl);
            }

            //draw xyzs as Point objects
            var pt = ((FScheme.Value.Container)value).Item as XYZ;
            if (pt != null)
            {
                Type pointType = typeof(Point);
                MethodInfo[] pointTypeMethods = pointType.GetMethods(BindingFlags.Static | BindingFlags.Public);
                var method = pointTypeMethods.FirstOrDefault(x => x.Name == "CreatePoint");

                if (method != null)
                {
                    var args = new object[3];
                    args[0] = pt.X;
                    args[1] = pt.Y;
                    args[2] = pt.Z;
                    geoms.Add((Point)method.Invoke(null, args));
                }
            }

            return geoms;
        }
Пример #29
0
        /// <summary>
        /// Unwrap an FScheme value containing a number or a unit to a double.
        /// If the value contains a unit object, convert the internal value of the
        /// unit object to the units required by the host application as specified
        /// in the preference settings. If the value contains a number, do not 
        /// apply a conversion.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static FScheme.Value UnwrapToDoubleWithHostUnitConversion(FScheme.Value value)
        {
            if (value.IsList)
            {
                //recursively convert items in list
                return ConvertListToHostUnits((FScheme.Value.List)value);
            }

            if (value.IsContainer)
            {
                var unit = ((FScheme.Value.Container)value).Item as SIUnit;
                if (unit != null)
                {
                    return FScheme.Value.NewNumber(unit.ConvertToHostUnits());
                }
            }

            return value;
        }
Пример #30
0
 public void Log(FScheme.Expression expression)
 {
     Log(FScheme.printExpression("\t", expression));
 }
Пример #31
0
        public static string PrintValue(
            FScheme.Value eIn,
            int currentListIndex,
            int maxListIndex,
            int currentDepth,
            int maxDepth,
            int maxStringLength = 20)
        {
            if (eIn == null)
                return "<null>";

            string accString = String.Concat(Enumerable.Repeat("  ", currentDepth));

            if (maxDepth == currentDepth || currentListIndex == maxListIndex)
            {
                accString += "...";
                return accString;
            }

            if (eIn.IsContainer)
            {
                string str = (eIn as FScheme.Value.Container).Item != null
                                 ? (eIn as FScheme.Value.Container).Item.ToString()
                                 : "<empty>";

                accString += str;
            }
            else if (eIn.IsFunction)
                accString += "<function>";
            else if (eIn.IsList)
            {
                accString += "List";

                FSharpList<FScheme.Value> list = (eIn as FScheme.Value.List).Item;

                if (!list.Any())
                    accString += " (empty)";

                // when children will be at maxDepth, just do 1
                if (currentDepth + 1 == maxDepth)
                    maxListIndex = 0;

                // build all elements of sub list
                accString =
                    list.Select((x, i) => new { Element = x, Index = i })
                        .TakeWhile(e => e.Index <= maxListIndex)
                        .Aggregate(
                            accString,
                            (current, e) =>
                            current + "\n"
                            + PrintValue(e.Element, e.Index, maxListIndex, currentDepth + 1, maxDepth, maxStringLength));
            }
            else if (eIn.IsNumber)
            {
                double num = (eIn as FScheme.Value.Number).Item;
                var numFloat = (float)num;
                accString += numFloat.ToString();
            }
            else if (eIn.IsString)
            {
                string str = (eIn as FScheme.Value.String).Item;
                if (str.Length > maxStringLength)
                    str = str.Substring(0, maxStringLength) + "...";

                accString += "\"" + str + "\"";
            }
            else if (eIn.IsSymbol)
                accString += "<" + (eIn as FScheme.Value.Symbol).Item + ">";

            return accString;
        }
Пример #32
0
        protected internal virtual void Run(bool RunInDebug, IEnumerable<dynNodeModel> topElements, FScheme.Expression runningExpression)
        {
            //Print some stuff if we're in debug mode
            if (RunInDebug)
            {
            // NOPE
                //if (dynSettings.Bench != null)
                //{
                //    //string exp = FScheme.print(runningExpression);
                //    //dynSettings.Bench.Dispatcher.Invoke(new Action(
                //    //                            delegate
                //    //                            {
                //    //                                foreach (dynNodeModel node in topElements)
                //    //                                {
                //    //                                    string exp = node.PrintExpression();
                //    //                                    dynSettings.Controller.DynamoViewModel.Log("> " + exp);
                //    //                                }
                //    //                            }
                //    //                            ));
                //}
            }

            try
            {
                //Evaluate the expression
                FScheme.Value expr = this.FSchemeEnv.Evaluate(runningExpression);

                if (dynSettings.Bench != null)
                {
                    //Print some more stuff if we're in debug mode
                    if (RunInDebug && expr != null)
                    {
            // NOPE
                        //dynSettings.Bench.Dispatcher.Invoke(new Action(
                        //                            () =>
                        //                            dynSettings.Controller.DynamoViewModel.Log(FScheme.print(expr))
                        //                            ));
                    }
                }
            }
            catch (CancelEvaluationException ex)
            {
                /* Evaluation was cancelled */

                OnRunCancelled(false);
                //this.RunCancelled = false;
                if (ex.Force)
                    runAgain = false;
            }
            catch (Exception ex)
            {
                /* Evaluation failed due to error */
            // NOPE
                //if (dynSettings.Bench != null)
                //{
                //    //Print unhandled exception
                //    if (ex.Message.Length > 0)
                //    {
                //        dynSettings.Bench.Dispatcher.Invoke(new Action(
                //                                    delegate { dynSettings.Controller.DynamoViewModel.Log(ex); }
                //                                    ));
                //    }
                //}

                OnRunCancelled(true);
                RunCancelled = true;
                runAgain = false;
            }

            OnEvaluationCompleted();
        }
Пример #33
0
        public static Autodesk.Revit.DB.CurveLoop CurveLoopFromContainer(FScheme.Value.Container curveOrCurveLoop)
        {
            var pathLoopBoxed = curveOrCurveLoop.Item;
            Autodesk.Revit.DB.CurveLoop curveLoop;
            var loop = pathLoopBoxed as Autodesk.Revit.DB.CurveLoop;
            if (loop != null)
            {
                curveLoop = loop;
            }
            else
            {
                curveLoop = new Autodesk.Revit.DB.CurveLoop();
                curveLoop.Append((Autodesk.Revit.DB.Curve)pathLoopBoxed);
            }

            return curveLoop;
        }
Пример #34
0
 public static FScheme.Value ConvertAsAtom(FScheme.Value v)
 {
     if (v == null)
     {
         return FScheme.Value.NewString("");
     }
     else if (v.IsString || v.IsNumber)
     {
         return v;
     }
     else
     {
         return FScheme.Value.NewString(v.ToString());
     }
 }
Пример #35
0
 public void Log(FScheme.Expression expression)
 {
     Log(FScheme.printExpression("\t", expression));
 }
Пример #36
0
 public static List<FScheme.Value> ConvertRow(FScheme.Value v)
 {
     if (v.IsString || v.IsNumber)
     {
         return new List<FScheme.Value>() {v};
     }
     else if (v.IsList)
     {
         return ((FScheme.Value.List) v).Item.Select(ConvertAsAtom).ToList();
     }
     else
     {
         return new List<FScheme.Value>() {ConvertAsAtom(v)};
     }
 }
Пример #37
0
        protected override void Run(List<NodeModel> topElements, FScheme.Expression runningExpression)
        {
            var model = (DynamoRevitViewModel)DynamoViewModel;

            //If we are not running in debug...
            if (!DynamoViewModel.RunInDebug)
            {
                //Do we need manual transaction control?
                bool manualTrans = topElements.Any(CheckManualTransaction.TraverseUntilAny);

                //Can we avoid running everything in the Revit Idle thread?
                bool noIdleThread = manualTrans ||
                    !topElements.Any(CheckRequiresTransaction.TraverseUntilAny);

                //If we don't need to be in the idle thread...
                if (noIdleThread || IsTestMode)
                {
                    //DynamoLogger.Instance.Log("Running expression in evaluation thread...");
                    TransMode = TransactionMode.Manual; //Manual transaction control

                    if (IsTestMode)
                        TransMode = TransactionMode.Automatic;

                    InIdleThread = false; //Not in idle thread at the moment
                    base.Run(topElements, runningExpression); //Just run the Run Delegate
                }
                else //otherwise...
                {
                    //DynamoLogger.Instance.Log("Running expression in Revit's Idle thread...");
                    TransMode = TransactionMode.Automatic; //Automatic transaction control

                    Debug.WriteLine("Adding a run to the idle stack.");
                    InIdleThread = true; //Now in the idle thread.
                    IdlePromise.ExecuteOnIdle(
                        () => base.Run(topElements, runningExpression),
                        false); //Execute the Run Delegate in the Idle thread.

                }
            }
            else //If we are in debug mode...
            {
                TransMode = TransactionMode.Debug; //Debug transaction control
                InIdleThread = true; //Everything will be evaluated in the idle thread.

                DynamoLogger.Instance.Log("Running expression in debug.");

                //Execute the Run Delegate.
                base.Run(topElements, runningExpression);
            }
        }
Пример #38
0
        public List<List<FScheme.Value>> ConvertTo2DList(FScheme.Value v)
        {
            if (v.IsList)
            {
                return ((FScheme.Value.List)v).Item.Select(ConvertRow).ToList();
            }

            var list = new List<List<FScheme.Value>>();
            list.Add(ConvertRow(v));
            return list;
        }
Пример #39
0
 /// <summary>
 /// Log an expression
 /// </summary>
 /// <param name="expression"></param>
 public void Log(FScheme.Expression expression)
 {
     Instance.Log(FScheme.printExpression("\t", expression), LogLevel.Console);
 }
Пример #40
0
        protected virtual void Run(List<NodeModel> topElements, FScheme.Expression runningExpression)
        {
            //Print some stuff if we're in debug mode
            if (DynamoViewModel.RunInDebug)
            {
                if (dynSettings.Controller.UIDispatcher != null)
                {
                    foreach (string exp in topElements.Select(node => node.PrintExpression()))
                        DynamoLogger.Instance.Log("> " + exp);
                }
            }

            try
            {
                //Evaluate the expression
                FScheme.Value expr = FSchemeEnvironment.Evaluate(runningExpression);

                if (dynSettings.Controller.UIDispatcher != null)
                {
                    //Print some more stuff if we're in debug mode
                    if (DynamoViewModel.RunInDebug && expr != null)
                    {
                        DynamoLogger.Instance.Log("Evaluating the expression...");
                        DynamoLogger.Instance.Log(FScheme.print(expr));
                    }
                }
            }
            catch (CancelEvaluationException ex)
            {
                /* Evaluation was cancelled */

                OnRunCancelled(false);
                RunCancelled = false;
                if (ex.Force)
                    runAgain = false;
            }
            catch (Exception ex)
            {
                /* Evaluation failed due to error */

                DynamoLogger.Instance.Log(ex);

                OnRunCancelled(true);
                RunCancelled = true;
                runAgain = false;

                //If we are testing, we need to throw an exception here
                //which will, in turn, throw an Assert.Fail in the
                //Evaluation thread.
                if (Testing)
                    throw new Exception(ex.Message);
            }

            OnEvaluationCompleted(this, EventArgs.Empty);
        }
Пример #41
0
 //Sets the environment contained by this EnvironmentWrapper
 //to the one provided by FScheme by default.
 public EnvironmentWrapper()
 {
     env = FScheme.CreateEnvironments();
 }
Пример #42
0
 void DrawPython(FScheme.Value val, string id)
 {
     //DrawContainers(val, id);
 }