diff --git a/Directory.Build.props b/Directory.Build.props
index 14c1434..c30b688 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -6,7 +6,7 @@
true
netstandard2.0
en
- 9.18.4
+ 9.19.3
true
diff --git a/Documentation/Release_Notes/ReleaseNotes_3_0.md b/Documentation/Release_Notes/ReleaseNotes_3_0.md
index d79dc89..dd07d32 100644
--- a/Documentation/Release_Notes/ReleaseNotes_3_0.md
+++ b/Documentation/Release_Notes/ReleaseNotes_3_0.md
@@ -4,7 +4,7 @@ Version 3.0 is a breaking release. This means that what was previously supported
## New Features
-- Python future compatibility. This version will support Python 3.7 and all newer / future versions.
+- Improved Python compatibility. This version will support Python 3.7 - 3.11.
- It is no longer necessary to 'build' the python modules before using them.
- Every .NET type can be inherited from and every plugin type can be created.
- Added support for Mac OS.
@@ -18,6 +18,6 @@ Version 3.0 is a breaking release. This means that what was previously supported
- Python 2.X is no longer supported.
- Python versions less or equal to 3.6 are also not supported.
-That means, at the time of writing Python 3.7, 3.8, 3.9, 3.10 and 3.11 are supported, but the new Python Plugin is future compatible, so 3.12 and onwards are expected to be supported as well.
+That means, at the time of writing Python 3.7, 3.8, 3.9, 3.10 and 3.11 are supported.
- It is no longer possible to build a C# DLL containing a C# API for the Python code.
diff --git a/OpenTap.Python.Examples/UserInputExample.py b/OpenTap.Python.Examples/UserInputExample.py
index 3d36eb1..c67b4bb 100644
--- a/OpenTap.Python.Examples/UserInputExample.py
+++ b/OpenTap.Python.Examples/UserInputExample.py
@@ -4,12 +4,18 @@
from System import String, Object, Double
import System.Threading
import OpenTap
-from OpenTap import Display
+from OpenTap import Display, Submit
from opentap import *
+from enum import Enum
+
+
+class OkEnum(Enum):
+ OK = 1
# Notice, this class inherits from System.Object(see line 4), a .NET class, not the default python object class.
class BasicUserInput(Object):
Frequency = property(Double, 1.0).add_attribute(Display("Frequency", "The selected frequency."))
+ Ok = property(OkEnum, OkEnum.OK).add_attribute(Submit())
def __init__(self):
super().__init__()
diff --git a/OpenTap.Python.ProjectTemplate/OpenTap.Python.ProjectTemplate.Api/OpenTap.Python.ProjectTemplate.Api.csproj b/OpenTap.Python.ProjectTemplate/OpenTap.Python.ProjectTemplate.Api/OpenTap.Python.ProjectTemplate.Api.csproj
index b06dd35..5520271 100644
--- a/OpenTap.Python.ProjectTemplate/OpenTap.Python.ProjectTemplate.Api/OpenTap.Python.ProjectTemplate.Api.csproj
+++ b/OpenTap.Python.ProjectTemplate/OpenTap.Python.ProjectTemplate.Api/OpenTap.Python.ProjectTemplate.Api.csproj
@@ -9,9 +9,9 @@
-
-
-
+
+
+
diff --git a/OpenTap.Python/DebugServer.cs b/OpenTap.Python/DebugServer.cs
new file mode 100644
index 0000000..8f1f06a
--- /dev/null
+++ b/OpenTap.Python/DebugServer.cs
@@ -0,0 +1,60 @@
+using System.Net.Sockets;
+using Python.Runtime;
+
+namespace OpenTap.Python;
+
+/// A custom debug server emulating what pydebug can do.
+class DebugServer
+{
+ public static DebugServer Instance { get; } = new ();
+
+ public int Port { get; set; }
+
+ TcpListener listener;
+ TapThread thread;
+ DebugServerClientHandler handler;
+
+ private DebugServer(){}
+
+ public void Start()
+ {
+ listener = new TcpListener(Port);
+ listener.Start();
+ thread = TapThread.Start(AcceptClient);
+ }
+
+ void AcceptClient()
+ {
+ while (TapThread.Current.AbortToken.IsCancellationRequested == false)
+ {
+ var cli = listener.AcceptTcpClient();
+ if (handler != null)
+ {
+ Log.CreateSource("Debug").Error("Only one debugging client can be connected at a time.");
+ cli.Close();
+ continue;
+ }
+
+ handler = new DebugServerClientHandler(cli);
+ handler.Disconnected += () => handler = null;
+ }
+ }
+
+ public int TraceCallback(PyObject arg1, Runtime.PyFrameObject arg2, Runtime.TraceWhat arg3, PyObject arg4)
+ {
+ // the active threads always needs to be updated.
+ if(arg3 == Runtime.TraceWhat.Call)
+ DebugServerClientHandler.GetThreadId(TapThread.Current);
+ handler?.TraceCallback(arg1, arg2, arg3, arg4);
+ return 0;
+ }
+
+ public void Stop()
+ {
+ listener.Stop();
+ thread.Abort();
+ thread = null;
+ listener = null;
+ handler = null;
+ }
+}
\ No newline at end of file
diff --git a/OpenTap.Python/DebugServerClientHandler.cs b/OpenTap.Python/DebugServerClientHandler.cs
new file mode 100644
index 0000000..1a66ae9
--- /dev/null
+++ b/OpenTap.Python/DebugServerClientHandler.cs
@@ -0,0 +1,756 @@
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Net.Sockets;
+using System.Runtime.CompilerServices;
+using System.Text.Json;
+using System.Threading;
+using Python.Runtime;
+
+namespace OpenTap.Python;
+
+///
+/// This class emulated the behavior of the pydebug server, but it is written entirely in C#.
+///
+/// This implements the Debug Adapter Protocol also described here: https://microsoft.github.io/debug-adapter-protocol/specification
+///
+class DebugServerClientHandler
+{
+ record BreakStackFrames(StackFrame[] stackFrames, int totalFrames, int threadId);
+ record StackFrame(int id, string name, int line, int column, object source);
+ class NextLine
+ {
+ public int ThreadId { get; set; }
+ public int CurrentLine { get; set; }
+ public string Name { get; set; }
+ public int BreakLevel { get; set; }
+ public string Mode { get; set; }
+ }
+
+ static readonly object successObject = new ();
+ static int threadCounter = 0;
+ static readonly ConditionalWeakTable knownThreads = new();
+ static readonly List> threads = new();
+
+ // a running number for marking each response.
+ int responseSeq;
+
+ readonly ConcurrentQueue<(string, object)> events = new ();
+ readonly TcpClient client;
+ readonly StreamReader reader;
+ readonly StreamWriter writer;
+ readonly object clientLock = new ();
+ readonly Dictionary> breakPoints = new ();
+
+ // incremented when execution is waiting for continuing. When it is non-zero,
+ // it means that we are waiting to continue.
+ int isWaiting;
+ object debugState;
+
+ // These values are set when a breakpoint is hit, otherwise they wont
+ // have valid state.
+ BreakStackFrames breakStackFrames = null;
+ ConcurrentQueue processor;
+ CancellationToken breakCancel;
+ Dictionary ScopeVariableReferences;
+ Dictionary<(PyObject, PyObject), int> ScopeVariableReferenceLookup;
+
+ readonly ConcurrentDictionary sourceReference = new();
+
+ public DebugServerClientHandler(TcpClient client)
+ {
+ this.client = client;
+ var stream = client.GetStream();
+ reader = new StreamReader(stream);
+ writer = new StreamWriter(stream);
+ TapThread.Start(ProcessRequests);
+ TapThread.Start(ProcessEvents);
+ }
+
+ void SendMessage(object obj)
+ {
+ var retstr = JsonSerializer.Serialize(obj);
+ var enc = $"Content-Length: {retstr.Length}\r\n\r\n";
+ var content = enc + retstr;
+ writer.Write(content);
+ writer.Flush();
+ }
+
+ JsonDocument ReadMessage()
+ {
+ int contentLength = 0;
+ while (true)
+ {
+ var line = reader.ReadLine();
+ if (line == null) break;
+ var s = line.Split(':').Select(x => x.Trim()).ToArray();
+ if (s.Length > 1)
+ {
+ if (s[0] == "Content-Length")
+ {
+ contentLength = int.Parse(s[1]);
+ }
+ continue;
+ }
+
+ if (line == "")
+ {
+ char[] bytes = new char[contentLength];
+ reader.Read(bytes, 0, contentLength);
+ int reqSeq = -1;
+ string type = null;
+
+ var js = JsonDocument.Parse(bytes);
+
+ if (js.RootElement.TryGetProperty("type", out var reqElem))
+ type = reqElem.GetString();
+
+ if (js.RootElement.TryGetProperty("seq", out var seqElem))
+ reqSeq = seqElem.GetInt32();
+
+ if (type != "request")
+ throw new Exception("Invalid type of message.");
+ if (reqSeq == -1)
+ throw new Exception("Invalid sequence number");
+ return js;
+ }
+ }
+
+ return null;
+ }
+
+ void ProcessEvents()
+ {
+ while (client.Connected)
+ {
+ TapThread.ThrowIfAborted();
+ if (events.TryDequeue(out var r))
+ {
+ lock (clientLock)
+ {
+ try
+ {
+ var evt = WrapEvent(r.Item1, r.Item2);
+ SendMessage(evt);
+ }
+ catch
+ {
+ // lost event
+ }
+ }
+ }
+ else
+ {
+ TapThread.Sleep(100);
+ }
+ }
+ }
+
+ void ProcessRequests()
+ {
+ try
+ {
+ while (client.Connected)
+ {
+ TapThread.ThrowIfAborted();
+ var msg = ReadMessage();
+ if (msg == null) continue;
+ var command = msg.RootElement.GetProperty("command").GetString();
+ var reqseq = msg.RootElement.GetProperty("seq").GetInt32();
+ lock (clientLock)
+ {
+ msg.RootElement.TryGetProperty("arguments", out var arguments);
+ try
+ {
+ var responseBody = ProcessCommand(command, arguments);
+ if (responseBody != null)
+ SendMessage(WrapResponse(command, responseBody, reqseq));
+ }
+ catch
+ {
+ // lost event.
+ }
+ }
+ }
+ }
+ finally
+ {
+ Disconnected?.Invoke();
+ }
+ }
+
+ object WrapEvent(string eventName, object body)
+ {
+ if (body == null || body == successObject)
+ {
+ return new
+ {
+ @event = eventName,
+ type = "event",
+ seq = Interlocked.Increment(ref responseSeq)
+ };
+ }
+
+ return new
+ {
+ @event = eventName,
+ type = "event",
+ seq = Interlocked.Increment(ref responseSeq),
+ body = body
+ };
+ }
+
+ object WrapResponse(string cmd, object body, int reqseq)
+ {
+ if (body == successObject)
+ {
+ return new
+ {
+ seq = Interlocked.Increment(ref responseSeq),
+ type = "response",
+ request_seq = reqseq,
+ success = true,
+ command = cmd
+ };
+ }
+ return new
+ {
+ seq = Interlocked.Increment(ref responseSeq),
+ type = "response",
+ request_seq = reqseq,
+ success = true,
+ command = cmd,
+ body = body
+ };
+ }
+
+ void PushEvent(string name, object evt)
+ {
+ events.Enqueue((name, evt));
+ }
+
+ object ProcessCommand(string command, JsonElement args)
+ {
+ switch (command)
+ {
+ case "initialize":
+ return InitializeRequest();
+ case "attach":
+ return AttachRequest(args);
+ case "setBreakpoints":
+ return SetBreakpointsRequest(args);
+ case "setFunctionBreakpoints":
+ return SetFunctionBreakpointsRequest(args);
+ case "setExceptionBreakpoints":
+ return SetExceptionBreakpointsRequest(args);
+ case "configurationDone":
+ return successObject;
+ case "threads":
+ return ThreadsRequest();
+ case "stackTrace":
+ return StackTraceRequest(args);
+ case "source":
+ return SourceRequest(args);
+ case "variables":
+ return VariablesRequest(args);
+ case "next":
+ return NextRequest(args);
+ case "continue":
+ return ContinueRequest(args);
+ case "stepIn":
+ return StepInRequest(args);
+ case "stepOut":
+ return StepOutRequest(args);
+ case "disconnect":
+ client.Close();
+ return successObject;
+ case "scopes":
+ return ScopesRequest(args);
+ }
+ return null;
+ }
+
+
+
+ object InitializeRequest()
+ {
+ PushEvent("initialized", successObject);
+ var exception_breakpoint_filters = new object[]
+ {
+ new {
+ filter= "raised",
+ label= "Raised Exceptions",
+ @default= false,
+ description= "Break whenever any exception is raised."
+ }
+ };
+
+ return new
+ {
+ supportsCompletionsRequest = true,
+ supportsConditionalBreakpoints = true,
+ supportsConfigurationDoneRequest = true,
+ supportsDebuggerProperties = true,
+ supportsDelayedStackTraceLoading = true,
+ supportsEvaluateForHovers = true,
+ supportsExceptionInfoRequest = true,
+ supportsExceptionOptions = true,
+ supportsFunctionBreakpoints = true,
+ supportsHitConditionalBreakpoints = true,
+ supportsLogPoints = true,
+ supportsModulesRequest = true,
+ supportsSetExpression = true,
+ supportsSetVariable = true,
+ supportsValueFormattingOptions = true,
+ supportsTerminateDebuggee = true,
+ supportsGotoTargetsRequest = true,
+ supportsClipboardContext = true,
+ exceptionBreakpointFilters = exception_breakpoint_filters,
+ supportsStepInTargetsRequest = true,
+ };
+ }
+
+ object AttachRequest(JsonElement args) => successObject;
+
+ object SetBreakpointsRequest(JsonElement args)
+ {
+ var idbase = breakPoints.Count;
+ var source = args.GetProperty("source");
+ var name = source.TryGetProperty("name", out var p) ? p.GetString() : "";
+ var path = source.GetProperty("path").GetString();
+ var lines = args.GetProperty("lines").EnumerateArray().Select(x => x.GetInt32()).ToArray();
+
+ breakPoints[name] = new HashSet(lines);
+
+ return new
+ {
+ breakpoints = lines.Select( (line, id) => new {
+ verified = true,
+ id = idbase + id,
+ line = line,
+ source = new
+ {
+ name = name,
+ path = path,
+ }
+ }).ToArray()
+ };
+ }
+
+ object SetFunctionBreakpointsRequest(JsonElement args)
+ {
+ /*var source = args.GetProperty("source");
+ var name = source.GetProperty("name").GetString();
+ var path = source.GetProperty("path").GetString();
+ var lines = source.GetProperty("lines").EnumerateArray().Select(x => x.GetInt32()).ToArray();*/
+ return new
+ {
+ breakpoints = Array.Empty