diff --git a/src/IronPythonExtension/IronPythonExtension.cs b/src/IronPythonExtension/IronPythonExtension.cs
deleted file mode 100644
index 38babc3b8ef..00000000000
--- a/src/IronPythonExtension/IronPythonExtension.cs
+++ /dev/null
@@ -1,94 +0,0 @@
-using System;
-using System.IO;
-using System.Reflection;
-using Dynamo.Extensions;
-using Dynamo.Logging;
-using Dynamo.PythonServices;
-
-namespace IronPythonExtension
-{
- ///
- /// This extension does nothing but loading DSIronPython to make IronPython engine
- /// available as one alternative Python evaluation option
- ///
- public class IronPythonExtension : IExtension, ILogSource
- {
- private const string PythonEvaluatorAssembly = "DSIronPython";
-
- ///
- /// Dispose function
- ///
- public void Dispose()
- {
- // Do nothing for now
- }
-
- ///
- /// Extension unique GUID
- ///
- public string UniqueId => "D7B449D7-4D54-47EF-B742-30C7BEDFBE92";
-
- ///
- /// Extension name
- ///
- public string Name => "IronPythonExtension";
-
- #region ILogSource
-
- public event Action MessageLogged;
- internal void OnMessageLogged(ILogMessage msg)
- {
- if (this.MessageLogged != null)
- {
- MessageLogged?.Invoke(msg);
- }
- }
- #endregion
-
- ///
- /// Action to be invoked when Dynamo begins to start up.
- ///
- ///
- public void Startup(StartupParams sp)
- {
- // Do nothing for now
- }
-
- ///
- /// Action to be invoked when the Dynamo has started up and is ready
- /// for user interaction.
- ///
- ///
- public void Ready(ReadyParams sp)
- {
- // Searches for DSIronPython engine binary in same folder with extension itself
- var targetDir = Path.GetDirectoryName(Assembly.GetAssembly(typeof(IronPythonExtension)).Location);
- var libraryLoader = sp.StartupParams.LibraryLoader;
- Assembly pythonEvaluatorLib = null;
- try
- {
- pythonEvaluatorLib = Assembly.LoadFrom(Path.Combine(targetDir, PythonEvaluatorAssembly + ".dll"));
- }
- catch (Exception ex)
- {
- // Most likely the IronPython engine is excluded in this case
- // but logging the exception message in case for diagnose
- OnMessageLogged(LogMessage.Info(ex.Message));
- return;
- }
- // Import IronPython Engine into VM, so Python node using IronPython engine could evaluate correctly
- if (pythonEvaluatorLib != null)
- {
- libraryLoader.LoadNodeLibrary(pythonEvaluatorLib);
- }
- }
-
- ///
- /// Action to be invoked when shutdown has begun.
- ///
- public void Shutdown()
- {
- // Do nothing for now
- }
- }
-}
diff --git a/src/IronPythonExtension/IronPythonExtension.csproj b/src/IronPythonExtension/IronPythonExtension.csproj
deleted file mode 100644
index 6eaba61943e..00000000000
--- a/src/IronPythonExtension/IronPythonExtension.csproj
+++ /dev/null
@@ -1,38 +0,0 @@
-
-
-
-
-
- {182FCA4E-B6EF-451F-9EC4-7BF2C622F4F7}
- Library
- Properties
- IronPythonExtension
- IronPythonExtension
-
-
-
- {7858fa8c-475f-4b8e-b468-1f8200778cf8}
- DynamoCore
- False
-
-
- {8872ca17-c10d-43b9-8393-5c5a57065eb0}
- PythonNodeModels
- False
-
-
- {ef879a10-041d-4c68-83e7-3192685f1bae}
- DynamoServices
- False
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/src/IronPythonExtension/IronPythonExtension_ExtensionDefinition.xml b/src/IronPythonExtension/IronPythonExtension_ExtensionDefinition.xml
deleted file mode 100644
index e2eb061ebad..00000000000
--- a/src/IronPythonExtension/IronPythonExtension_ExtensionDefinition.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-
- ..\IronPythonExtension.dll
- IronPythonExtension.IronPythonExtension
-
\ No newline at end of file
diff --git a/src/IronPythonExtension/Properties/AssemblyInfo.cs b/src/IronPythonExtension/Properties/AssemblyInfo.cs
deleted file mode 100644
index 20b6fa9f71a..00000000000
--- a/src/IronPythonExtension/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-using System.Reflection;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("IronPythonExtension")]
-[assembly: AssemblyCulture("")]
-
-// The following GUID is for the ID of the typelib if this project is exposed to COM
-[assembly: Guid("182fca4e-b6ef-451f-9ec4-7bf2c622f4f7")]
diff --git a/src/Libraries/DSCPython/CPythonEvaluator.cs b/src/Libraries/DSCPython/CPythonEvaluator.cs
index 5565f11aff0..4b792f15e03 100644
--- a/src/Libraries/DSCPython/CPythonEvaluator.cs
+++ b/src/Libraries/DSCPython/CPythonEvaluator.cs
@@ -131,13 +131,6 @@ public void Dispose()
}
}
- [SupressImportIntoVM]
- [Obsolete("Deprecated. Please use Dynamo.PythonServices.EvaluationState instead.")]
- public enum EvaluationState { Begin, Success, Failed }
-
- [SupressImportIntoVM]
- [Obsolete("Deprecated. Please use evaluation handlers from Dynamo.PythonServices instead.")]
- public delegate void EvaluationEventHandler(EvaluationState state, PyScope scope, string code, IList bindingValues);
///
/// Evaluates a Python script in the Dynamo context.
@@ -624,12 +617,7 @@ private static bool IsMarkedToSkipConversion(PyObject pyObj)
#region Evaluation events
- ///
- /// Emitted immediately before execution begins
- ///
- [SupressImportIntoVM]
- [Obsolete("Deprecated. Please use EvaluationStarted instead")]
- public static event EvaluationEventHandler EvaluationBegin;
+
///
@@ -638,13 +626,6 @@ private static bool IsMarkedToSkipConversion(PyObject pyObj)
[SupressImportIntoVM]
public override event EvaluationStartedEventHandler EvaluationStarted;
- ///
- /// Emitted immediately after execution ends or fails
- ///
- [SupressImportIntoVM]
- [Obsolete("Deprecated. Please use EvaluationFinished instead.")]
- public static event EvaluationEventHandler EvaluationEnd;
-
///
/// Emitted immediately after execution ends or fails
///
@@ -661,8 +642,6 @@ private void OnEvaluationBegin(PyScope scope,
string code,
IList bindingValues)
{
- // Call deprecated events until they are completely removed.
- EvaluationBegin?.Invoke(EvaluationState.Begin, scope, code, bindingValues);
if (EvaluationStarted != null)
{
@@ -686,11 +665,7 @@ private void OnEvaluationEnd(bool isSuccessful,
string code,
IList bindingValues)
{
- // Call deprecated events until they are completely removed.
- EvaluationEnd?.Invoke(isSuccessful ?
- EvaluationState.Success :
- EvaluationState.Failed, scope, code, bindingValues);
-
+
if (EvaluationFinished != null)
{
EvaluationFinished(isSuccessful ? Dynamo.PythonServices.EvaluationState.Success : Dynamo.PythonServices.EvaluationState.Failed,
diff --git a/src/Libraries/DSIronPython/DSIronPython.csproj b/src/Libraries/DSIronPython/DSIronPython.csproj
deleted file mode 100644
index 72c374e4b49..00000000000
--- a/src/Libraries/DSIronPython/DSIronPython.csproj
+++ /dev/null
@@ -1,54 +0,0 @@
-
-
-
-
-
- {9EEF4F42-6B3B-4358-9A8A-C2701539A822}
- Library
- Properties
- DSIronPython
- DSIronPython
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {7858FA8C-475F-4B8E-B468-1F8200778CF8}
- DynamoCore
- False
-
-
- {b5f435cb-0d8a-40b1-a4f7-5ecb3ce792a9}
- DynamoUtilities
- False
-
-
- {ef879a10-041d-4c68-83e7-3192685f1bae}
- DynamoServices
- False
-
-
- {c0d6dee5-5532-4345-9c66-4c00d7fdb8be}
- DesignScriptBuiltin
- False
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/src/Libraries/DSIronPython/IronPythonCodeCompletionDataCore.cs b/src/Libraries/DSIronPython/IronPythonCodeCompletionDataCore.cs
deleted file mode 100644
index 95da5ed0b72..00000000000
--- a/src/Libraries/DSIronPython/IronPythonCodeCompletionDataCore.cs
+++ /dev/null
@@ -1,18 +0,0 @@
-using Autodesk.DesignScript.Interfaces;
-using Dynamo.PythonServices;
-
-namespace DSIronPython
-{
- ///
- /// Concrete type that gets returned and converted to an Avalonedit type implementing
- /// ICompletionData when used from WPF ScriptEditorContorl.
- ///
- internal class IronPythonCodeCompletionDataCore : PythonCodeCompletionDataCore
- {
- public IronPythonCodeCompletionDataCore(string text, string stub, bool isInstance,
- ExternalCodeCompletionType completionType, IExternalCodeCompletionProviderCore providerCore) :
- base(text, stub, isInstance, completionType, providerCore)
- {
- }
- }
-}
diff --git a/src/Libraries/DSIronPython/IronPythonCodeCompletionProviderCore.cs b/src/Libraries/DSIronPython/IronPythonCodeCompletionProviderCore.cs
deleted file mode 100644
index 7d8cccc1cd7..00000000000
--- a/src/Libraries/DSIronPython/IronPythonCodeCompletionProviderCore.cs
+++ /dev/null
@@ -1,488 +0,0 @@
-using Autodesk.DesignScript.Interfaces;
-using Dynamo.Logging;
-using Dynamo.PythonServices;
-using IronPython.Runtime;
-using IronPython.Runtime.Types;
-using Microsoft.Scripting;
-using Microsoft.Scripting.Actions;
-using Microsoft.Scripting.Hosting;
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Reflection;
-using System.Text.RegularExpressions;
-
-namespace DSIronPython
-{
- internal class IronPythonCodeCompletionProviderCore : PythonCodeCompletionProviderCommon, ILegacyPythonCompletionCore, ILogSource, IDisposable
- {
- #region Private Members
- internal static readonly string clrTypeLookup = "clr.GetClrType({0}) if (\"{0}\" in locals() or \"{0}\" in __builtins__) and isinstance({0}, type) else None";
-
- private ScriptEngine engine;
- ///
- /// The engine used for autocompletion. This essentially keeps
- /// track of the state of the editor, allowing access to variable types and
- /// imported symbols.
- ///
- private ScriptScope scope;
- #endregion
-
- #region BACKING LEGACY CLASS DO NOT MODIFY UNTIL 3
- //ILegacyPythonCompletionCore implementations
- //!!!- do not modify these signatures until that class is removed.
- //We do not know if anyone was using that class, but we needed to remove the compile
- //time references between PythonNodeModels and DSIronPython to support dynamically loading
- //python versions.
-
- //note that the public members below are not really public (this is an internal class)
- //but must be marked that way to satisfy the legacy interface
-
- ///
- /// The engine used for autocompletion. This essentially keeps
- /// track of the state of the editor, allowing access to variable types and
- /// imported symbols.
- ///
- public object Engine
- {
- get { return engine; }
- set { engine = (ScriptEngine)value; }
- }
- ///
- /// The scope used by the engine. This is where all the loaded symbols
- /// are stored. It's essentially an environment dictionary.
- ///
- public object Scope
- {
- get { return scope; }
- set { scope = (ScriptScope)value; }
- }
- ///
- /// List all of the members in a CLR Namespace
- ///
- /// A reference to the module
- /// The name of the module
- /// A list of completion data for the namespace
- public IEnumerable> EnumerateMembersFromTracker(object nameSpaceTracker, string name)
- {
- var items = new List>();
- var ns = nameSpaceTracker as NamespaceTracker;
- foreach (var member in ns)
- {
- if (member.Value is NamespaceTracker)
- {
- items.Add(Tuple.Create(member.Key, name, false, ExternalCodeCompletionType.Namespace));
- }
- else if (member.Value is FieldTracker)
- {
- items.Add(Tuple.Create(member.Key, name, false, ExternalCodeCompletionType.Field));
- }
- else if (member.Value is PropertyTracker)
- {
- items.Add(Tuple.Create(member.Key, name, false, ExternalCodeCompletionType.Property));
- }
- else if (member.Value is TypeTracker)
- {
- items.Add(Tuple.Create(member.Key, name, false, ExternalCodeCompletionType.Class));
- }
- }
-
- return items;
- }
- public new IEnumerable> EnumerateMembers(Type type, string name)
- {
- return base.EnumerateMembers(type, name);
- }
- ///
- /// List all of the members in a PythonModule
- ///
- /// A reference to the module
- /// The name of the module
- /// A list of completion data for the module
- public IEnumerable> EnumerateMembers(object module, string name)
- {
- var items = new List>();
- var d = (module as PythonModule).Get__dict__();
-
- foreach (var member in d)
- {
- var completionType = member.Value is BuiltinFunction ? ExternalCodeCompletionType.Method : ExternalCodeCompletionType.Field;
- items.Add(Tuple.Create((string)member.Key, name, false, completionType));
- }
-
- return items;
- }
- ///
- /// Recursively lookup a member in a given namespace.
- ///
- /// A name for a type, possibly delimited by periods.
- /// The namespace
- /// The type as an object
- public object LookupMember(string name, object nameSpaceTracker)
- {
- if (!(nameSpaceTracker is NamespaceTracker))
- {
- throw new ArgumentException("parameter n must be of type NameSpaceTracker");
- }
- var nst = nameSpaceTracker as NamespaceTracker;
- object varOutput;
-
- var periodIndex = name.IndexOf('.');
- if (periodIndex == -1)
- {
- if (nst.TryGetValue(name, out varOutput))
- {
- return varOutput;
- }
- return null;
- }
-
- var currentName = name.Substring(0, periodIndex);
- var theRest = name.Substring(periodIndex + 1);
-
- if (nst.TryGetValue(currentName, out varOutput))
- {
- if (varOutput is NamespaceTracker)
- {
- return LookupMember(theRest, varOutput as NamespaceTracker);
- }
- }
- return null;
- }
- ///
- /// Recursively lookup a variable in the _scope
- ///
- /// A name for a type, possibly delimited by periods.
- /// The type as an object
- public object LookupMember(string name)
- {
- object varOutput;
-
- var periodIndex = name.IndexOf('.');
- if (periodIndex == -1)
- {
- if (scope.TryGetVariable(name, out varOutput))
- {
- return varOutput;
- }
- return null;
- }
- var currentName = name.Substring(0, periodIndex);
- var theRest = name.Substring(periodIndex + 1);
-
- if (scope.TryGetVariable(currentName, out varOutput))
- {
- if (varOutput is NamespaceTracker)
- {
- return LookupMember(theRest, varOutput as NamespaceTracker);
- }
- }
- return null;
-
- }
- public new void UpdateImportedTypes(string code)
- {
- base.UpdateImportedTypes(code);
- }
- public new void UpdateVariableTypes(string code)
- {
- base.UpdateVariableTypes(code);
- }
- public new Dictionary FindAllVariableAssignments(string code)
- {
- return base.FindAllVariableAssignments(code);
- }
- public new Dictionary> FindAllVariables(string code)
- {
- return base.FindAllVariables(code);
- }
- public new Type TryGetType(string name)
- {
- return base.TryGetType(name);
- }
- #endregion
-
- #region PythonCodeCompletionProviderCommon implementations
- ///
- /// Generate completion data for the specified text, while import the given types into the
- /// scope and discovering variable assignments.
- ///
- /// The code to parse
- /// Determines if the entire namespace should be used
- /// Return a list of IExternalCodeCompletionData
- public override IExternalCodeCompletionData[] GetCompletionData(string code, bool expand = false)
- {
- IEnumerable items = new List();
-
- if (code.Contains("\"\"\""))
- {
- code = StripDocStrings(code);
- }
-
- UpdateImportedTypes(code);
- UpdateVariableTypes(code); // Possibly use hindley-milner in the future
-
- // If expand param is true use the entire namespace from the line of code
- // Else just return the last name of the namespace
- string name = expand ? GetLastNameSpace(code) :
- GetLastName(code);
- if (!String.IsNullOrEmpty(name))
- {
- try
- {
- // Attempt to get type using naming
- Type type = expand ? TryGetTypeFromFullName(name) : TryGetType(name);
-
- // CLR type
- if (type != null)
- {
- items = EnumerateMembers(type, name).Select(x => new IronPythonCodeCompletionDataCore(x.Item1, x.Item2, x.Item3, x.Item4, this));
- }
- // Variable type
- else if (VariableTypes.TryGetValue(name, out type))
- {
- items = EnumerateMembers(type, name).Select(x => new IronPythonCodeCompletionDataCore(x.Item1, x.Item2, x.Item3, x.Item4, this));
- }
- else
- {
- var mem = LookupMember(name);
- var namespaceTracker = mem as NamespaceTracker;
-
- // Namespace type
- if (namespaceTracker != null)
- {
- items = EnumerateMembersFromTracker(namespaceTracker, name).Select(x => new IronPythonCodeCompletionDataCore(x.Item1, x.Item2, x.Item3, x.Item4, this));
- }
- else
- {
- var pythonModule = mem as PythonModule;
-
- // Python Module type
- if (pythonModule != null)
- {
- items = EnumerateMembers(pythonModule, name).Select(x => new IronPythonCodeCompletionDataCore(x.Item1, x.Item2, x.Item3, x.Item4, this));
- }
- // Python type
- else if (mem is PythonType)
- {
- // Shows static and instance methods in the same way :(
- var value = ClrModule.GetClrType(mem as PythonType);
-
- if (value != null)
- {
- items = EnumerateMembers(value, name).Select(x => new IronPythonCodeCompletionDataCore(x.Item1, x.Item2, x.Item3, x.Item4, this));
- }
- }
- }
- }
- }
- catch (Exception ex)
- {
- Log(ex.ToString());
- }
- }
-
- // If unable to find matching results and expand was set to false,
- // try again using the full namespace (set expand to true)
- if (!items.Any() && !expand)
- {
- return GetCompletionData(code, true);
- }
-
- return items.ToArray();
- }
-
- ///
- /// Used to determine if this IExternalCodeCompletionProviderCore can provide completions for the given engine.
- ///
- ///
- ///
- public override bool IsSupportedEngine(string engineName)
- {
- // Do not reference 'PythonEngineManager.IronPython2EngineName' here
- // because it will break compatibility with Dynamo2.13.X
- //
- //if (engineName == PythonEngineManager.IronPython2EngineName)
- if (engineName == "IronPython2")
- {
- return true;
- }
- return false;
- }
-
- ///
- /// Used to load initialize libraries and types that should be available by default.
- ///
- ///
- public override void Initialize(string dynamoCorePath)
- {
- var pythonLibDir = string.Empty;
- var executionPath = Assembly.GetExecutingAssembly().Location;
- // Determine if the Python Standard Library is available in the DynamoCore path
- if (!String.IsNullOrEmpty(dynamoCorePath))
- {
- pythonLibDir = Path.Combine(dynamoCorePath, IronPythonEvaluator.PythonLibName);
- }
-
- // If IronPython.Std folder is excluded from DynamoCore (which could be user mistake or integrator exclusion)
- if (!Directory.Exists(pythonLibDir))
- {
- // Try to load IronPython from extension package
- pythonLibDir = Path.Combine((new DirectoryInfo(Path.GetDirectoryName(executionPath))).Parent.FullName, IronPythonEvaluator.packageExtraFolderName, IronPythonEvaluator.PythonLibName);
- }
-
- if (!String.IsNullOrEmpty(pythonLibDir))
- {
- // Try to load Python Standard Library Type for autocomplete
- try
- {
- var pyLibImports = String.Format("import sys\nsys.path.append(r'{0}')\n", pythonLibDir);
- engine.CreateScriptSourceFromString(pyLibImports, SourceCodeKind.Statements).Execute(scope);
- }
- catch (Exception e)
- {
- Log(e.ToString());
- Log("Failed to register IronPython's native library. Python autocomplete will not see standard modules.");
- }
- }
- else
- {
- Log("Valid IronPython Standard Library not found. Python autocomplete will not see native modules.");
- }
- }
-
- protected override object GetDescriptionObject(string docCommand)
- {
- try
- {
-
- return engine.CreateScriptSourceFromString(docCommand, SourceCodeKind.Expression).Execute(scope);
- }
- catch
- {
- //This empty catch block is intentional-
- //because we are using a python engine to evaluate the completions
- //but this engine has not actually loaded the types, it will throw lots of exceptions
- //we wish to suppress.
- }
-
- return null;
- }
- protected override object EvaluateScript(string script, PythonScriptType evalType)
- {
- switch (evalType)
- {
- case PythonScriptType.Expression:
- return engine.CreateScriptSourceFromString(script, SourceCodeKind.Expression).Execute(scope);
- case PythonScriptType.SingleStatement:
- return engine.CreateScriptSourceFromString(script, SourceCodeKind.SingleStatement).Execute(scope);
- case PythonScriptType.Statements:
- return engine.CreateScriptSourceFromString(script, SourceCodeKind.Statements).Execute(scope);
- }
- return null;
- }
-
- protected override void LogError(string msg)
- {
- Log(msg);
- }
-
- protected internal override bool ScopeHasVariable(string name)
- {
- return scope.ContainsVariable(name);
- }
-
- protected override Type GetCLRType(string name)
- {
- return EvaluateScript(String.Format(clrTypeLookup, name), PythonScriptType.Expression) as Type;
- }
- #endregion
-
- #region constructor
-
- public IronPythonCodeCompletionProviderCore()
- {
- engine = IronPython.Hosting.Python.CreateEngine();
- scope = engine.CreateScope();
-
- VariableTypes = new Dictionary();
- ImportedTypes = new Dictionary();
- ClrModules = new HashSet();
- BadStatements = new Dictionary();
-
- // Special case for python variables defined as null
- ImportedTypes["None"] = null;
-
- BasicVariableTypes = new List>();
-
- BasicVariableTypes.Add(Tuple.Create(STRING_VARIABLE, typeof(string)));
- BasicVariableTypes.Add(Tuple.Create(DOUBLE_VARIABLE, typeof(double)));
- BasicVariableTypes.Add(Tuple.Create(INT_VARIABLE, typeof(int)));
- BasicVariableTypes.Add(Tuple.Create(LIST_VARIABLE, typeof(IronPython.Runtime.List)));
- BasicVariableTypes.Add(Tuple.Create(DICT_VARIABLE, typeof(PythonDictionary)));
-
- // Main CLR module
- engine.CreateScriptSourceFromString("import clr\n", SourceCodeKind.SingleStatement).Execute(scope);
-
- var assemblies = AppDomain.CurrentDomain.GetAssemblies();
-
- // Determine if the Revit API is available in the given context
- if (assemblies.Any(x => x.GetName().Name == "RevitAPI"))
- {
- // Try to load Revit Type for autocomplete
- try
- {
- var revitImports =
- "clr.AddReference('RevitAPI')\nclr.AddReference('RevitAPIUI')\nfrom Autodesk.Revit.DB import *\nimport Autodesk\n";
-
- engine.CreateScriptSourceFromString(revitImports, SourceCodeKind.Statements).Execute(scope);
- ClrModules.Add("RevitAPI");
- ClrModules.Add("RevitAPIUI");
- }
- catch
- {
- Log("Failed to load Revit types for autocomplete. Python autocomplete will not see Autodesk namespace types.");
- }
- }
-
- // Determine if the ProtoGeometry is available in the given context
- if (assemblies.Any(x => x.GetName().Name == "ProtoGeometry"))
- {
- // Try to load ProtoGeometry Type for autocomplete
- try
- {
- var libGImports =
- "clr.AddReference('ProtoGeometry')\nfrom Autodesk.DesignScript.Geometry import *\n";
-
- engine.CreateScriptSourceFromString(libGImports, SourceCodeKind.Statements).Execute(scope);
- ClrModules.Add("ProtoGeometry");
- }
- catch (Exception e)
- {
- Log(e.ToString());
- Log("Failed to load ProtoGeometry types for autocomplete. Python autocomplete will not see Autodesk namespace types.");
- }
- }
-
-
- }
-
- #endregion
-
- #region ILogSource Implementation
- ///
- /// Raise this event to request loggers log this message.
- ///
- public event Action MessageLogged;
-
- private void Log( string message)
- {
- MessageLogged?.Invoke(LogMessage.Info(message));
- }
- #endregion
-
- public void Dispose()
- {}
- }
-}
diff --git a/src/Libraries/DSIronPython/IronPythonEvaluator.cs b/src/Libraries/DSIronPython/IronPythonEvaluator.cs
deleted file mode 100644
index ce1cd40505e..00000000000
--- a/src/Libraries/DSIronPython/IronPythonEvaluator.cs
+++ /dev/null
@@ -1,398 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Reflection;
-using Autodesk.DesignScript.Runtime;
-using Dynamo.Events;
-using Dynamo.Logging;
-using Dynamo.PythonServices;
-using Dynamo.PythonServices.EventHandlers;
-using Dynamo.Session;
-using Dynamo.Utilities;
-using IronPython.Hosting;
-
-using Microsoft.Scripting.Hosting;
-using Microsoft.Scripting.Utils;
-
-namespace DSIronPython
-{
- [SupressImportIntoVM]
- [Obsolete("Deprecated. Please use Dynamo.PythonServices.EvaluationState instead.")]
- public enum EvaluationState { Begin, Success, Failed }
-
- [SupressImportIntoVM]
- [Obsolete("Deprecated. Please use evaluation handlers from Dynamo.PythonServices instead.")]
- public delegate void EvaluationEventHandler(EvaluationState state,
- ScriptEngine engine,
- ScriptScope scope,
- string code,
- IList bindingValues);
-
- ///
- /// Evaluates a Python script in the Dynamo context.
- ///
- [IsVisibleInDynamoLibrary(false)]
- public class IronPythonEvaluator : Dynamo.PythonServices.PythonEngine
- {
- private const string DynamoPrintFuncName = "__dynamoprint__";
- /// stores a copy of the previously executed code
- private static string prev_code { get; set; }
- /// stores a copy of the previously compiled engine
- private static ScriptSource prev_script { get; set; }
-
- /// stores a reference to path of IronPython std lib
- private static string pythonLibDir { get; set; }
-
- ///
- /// Name of IronPython Std lib
- ///
- public const string PythonLibName = @"IronPython.StdLib.2.7.9";
-
- ///
- /// extra folder name in package folder
- ///
- public const string packageExtraFolderName = @"extra";
-
- // Do not reference 'PythonEngineManager.IronPython2EngineName' here
- // because it will break compatibility with Dynamo2.13.X
- //
- //public override string Name => PythonEngineManager.IronPython2EngineName;
-
- ///
- /// Returns the name of this Python engine implementation.
- /// This name will appear in the Dynamo's UI.
- ///
- public override string Name => "IronPython2";
-
- ///
- /// Use Lazy<PythonEngineManager> to make sure the Singleton class is only initialized once
- ///
- private static readonly Lazy
- lazy =
- new Lazy
- (() => new IronPythonEvaluator());
-
- ///
- /// The actual instance stored in the Singleton class
- ///
- internal static IronPythonEvaluator Instance { get { return lazy.Value; } }
-
- ///
- /// Attempts to build a path referencing the Python Standard Library,
- /// returns null if unable to retrieve a valid path.
- ///
- /// path to the Python Standard Library in Dynamo Core
- private static string PythonStandardLibPath()
- {
- // Attempt to get and cache the Dynamo Core directory path
- if (string.IsNullOrEmpty(pythonLibDir))
- {
- // Gather executing location, this could be DynamoCore folder or extension bin folder
- var executionPath = Assembly.GetExecutingAssembly().Location;
-
- // Assume the Python Standard Library is available in the DynamoCore path
- pythonLibDir = Path.Combine(Path.GetDirectoryName(executionPath), PythonLibName);
-
- // If IronPython.Std folder is excluded from DynamoCore (which could be user mistake or integrator exclusion)
- if (!Directory.Exists(pythonLibDir))
- {
- // Try to load IronPython from extension package
- pythonLibDir = Path.Combine((new DirectoryInfo(Path.GetDirectoryName(executionPath))).Parent.FullName, packageExtraFolderName, PythonLibName);
- }
- }
- return pythonLibDir;
- }
-
- ///
- /// Executes a Python script with custom variable names. Script may be a string
- /// read from a file, for example. Pass a list of names (matching the variable
- /// names in the script) to bindingNames and pass a corresponding list of values
- /// to bindingValues.
- ///
- /// Python script as a string.
- /// Names of values referenced in Python script.
- /// Values referenced in Python script.
- public override object Evaluate(
- string code,
- IList bindingNames,
- [ArbitraryDimensionArrayImport] IList bindingValues)
- {
- // TODO - it would be nice if users could modify a preference
- // setting enabling the ability to load additional paths
-
- // Container for paths that will be imported in the PythonEngine
- List paths = new List();
-
- // Attempt to get the Standard Python Library
- string stdLib = PythonStandardLibPath();
-
- if (code != prev_code)
- {
- ScriptEngine PythonEngine = Python.CreateEngine();
- if (!string.IsNullOrEmpty(stdLib))
- {
- paths = PythonEngine.GetSearchPaths().ToList();
- paths.Add(stdLib);
- }
-
- // If any paths were successfully retrieved, append them
- if (paths.Count > 0)
- {
- PythonEngine.SetSearchPaths(paths);
- }
-
- ScriptSource script = PythonEngine.CreateScriptSourceFromString(code);
- script.Compile();
- prev_script = script;
- prev_code = code;
- }
-
- ScriptEngine engine = prev_script.Engine;
- ScriptScope scope = engine.CreateScope();
- // For backwards compatibility: "sys" was imported by default due to a bug so we keep it that way
- scope.ImportModule("sys");
-
- ProcessAdditionalBindings(scope, bindingNames, bindingValues, engine);
-
- int amt = Math.Min(bindingNames.Count, bindingValues.Count);
-
- for (int i = 0; i < amt; i++)
- {
- scope.SetVariable((string)bindingNames[i], InputMarshaler.Marshal(bindingValues[i]));
- }
-
- try
- {
- OnEvaluationBegin(engine, scope, code, bindingValues);
- prev_script.Execute(scope);
- }
- catch (Exception e)
- {
- OnEvaluationEnd(false, engine, scope, code, bindingValues);
- var eo = engine.GetService();
- string error = eo.FormatException(e);
- throw new Exception(error);
- }
-
- OnEvaluationEnd(true, engine, scope, code, bindingValues);
-
- var result = scope.ContainsVariable("OUT") ? scope.GetVariable("OUT") : null;
-
- return OutputMarshaler.Marshal(result);
- }
-
- public static object EvaluateIronPythonScript(
- string code,
- IList bindingNames,
- [ArbitraryDimensionArrayImport] IList bindingValues)
- {
- return Instance.Evaluate(code, bindingNames, bindingValues);
- }
-
- ///
- /// Processes additional bindings that are not actual inputs.
- /// Currently, only the node name is received in this way.
- ///
- /// Python scope where execution will occur
- /// List of binding names received for evaluation
- /// List of binding values received for evaluation
- private static void ProcessAdditionalBindings(ScriptScope scope, IList bindingNames, IList bindingValues, ScriptEngine engine)
- {
- const string NodeNameInput = "Name";
- string nodeName;
- if (bindingNames.Count == 0 || !bindingNames[0].Equals(NodeNameInput))
- {
- // Defensive code to fallback in case the additional binding is not there, like
- // when the evaluator is called directly in tests, passing bindings manually.
- nodeName = "USER";
- }
- else
- {
- bindingNames.RemoveAt(0);
- nodeName = (string)bindingValues[0];
- bindingValues.RemoveAt(0);
- }
-
- // Session is null when running unit tests.
- if (ExecutionEvents.ActiveSession != null)
- {
- dynamic logger = ExecutionEvents.ActiveSession.GetParameterValue(ParameterKeys.Logger);
- Action logFunction = msg => logger.Log($"{nodeName}: {msg}", LogLevel.ConsoleOnly);
- scope.SetVariable(DynamoPrintFuncName, logFunction);
- ScriptSource source = engine.CreateScriptSourceFromString(RedirectPrint());
- source.Execute(scope);
- }
- }
-
- private static string RedirectPrint()
- {
- return String.Format(@"
-import sys
-
-class DynamoStdOut:
- def __init__(self, log_func):
- self.text = ''
- self.log_func = log_func
- def write(self, text):
- if text == '\n':
- self.log_func(self.text)
- self.text = ''
- else:
- self.text += text
-sys.stdout = DynamoStdOut({0})
-", DynamoPrintFuncName);
- }
-
- #region Marshalling
-
- ///
- /// Data Marshaler for all data coming into a Python node.
- ///
- [SupressImportIntoVM]
- public override object InputDataMarshaler
- {
- get
- {
- if (inputMarshaler == null)
- {
- inputMarshaler = new DataMarshaler();
- inputMarshaler.RegisterMarshaler(
- delegate(IList lst)
- {
- var pyList = new IronPython.Runtime.List();
- foreach (var item in lst.Cast