-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPythonConsole.cs
More file actions
237 lines (213 loc) · 8.47 KB
/
PythonConsole.cs
File metadata and controls
237 lines (213 loc) · 8.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
using ColossalFramework.Threading;
using PythonConsole.MoveIt;
using SkylinesPythonShared;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
namespace PythonConsole
{
public class PythonConsole
{
private static PythonConsole _instance;
public static PythonConsole Instance => _instance;
public RenderableObjManager RenderManager { get; private set; } = new RenderableObjManager();
private int _startUpTrials;
private TcpClient _client;
private Queue _simulationQueue;
private RemoteFuncManager _remoteFuncManager;
private volatile ConsoleState _state = ConsoleState.Initializing;
public ConsoleState State {
get => _state;
private set => _state = value;
}
public bool ExecuteSynchronously { get; private set; }
private Thread _thread;
private Stopwatch _stopWatch;
public PythonConsole(bool executeSynchronously)
{
Queue q = new Queue();
ExecuteSynchronously = executeSynchronously;
_simulationQueue = Queue.Synchronized(q);
_thread = new Thread(new ThreadStart(RemotePythonThread));
_thread.Name = "RemotePython";
_thread.Start();
if (!_thread.IsAlive) {
throw new Exception("Failed to start RemotePython thread!");
}
}
private void RemotePythonThread()
{
if(ModInfo.DoNotLaunchRemoteConsole.value) {
PrintAsync("Warning: Option 'Do not launch remote python console server' is enabled in settings. Turn it off if you don't know what you are doing.\n");
}
TcpClient.StartUpServer();
while(_startUpTrials < 10) {
try {
if (State == ConsoleState.Initializing) {
_client = TcpClient.CreateClient();
try {
_remoteFuncManager = new RemoteFuncManager(_client);
} catch(Exception ex) {
PrintAsync("Critical error in the python console mod\n" + ex);
break;
}
State = ConsoleState.Ready;
PrintAsync("Python engine ready\n");
break;
}
}
catch {
_startUpTrials++;
Thread.Sleep(500);
}
}
if(State == ConsoleState.Initializing) {
State = ConsoleState.Dead;
try { PrintAsync("Failed to start python engine\n"); } catch { }
return;
}
try {
while (State != ConsoleState.Dead) {
MessageHeader header = _client.GetMessageSync();
//UnityEngine.Debug.Log("In: " + header.messageType);
if(header.messageType == "c_exception") {
State = ConsoleState.Ready;
if(State != ConsoleState.ScriptAborting) {
PrintErrorAsync((string)header.payload);
}
continue;
}
if(header.messageType == "c_ready") {
State = ConsoleState.Ready;
continue;
}
if(State == ConsoleState.ScriptAborting) {
_client.SendMsg(null, "s_script_abort");
continue;
}
switch (header.messageType) {
case "c_output_message":
PrintAsync((string)header.payload);
break;
case "c_failed_to_compile":
State = ConsoleState.Ready;
PrintErrorAsync("Failed to compile: " + (string)header.payload);
break;
default:
if (header.messageType.StartsWith("c_callfunc_") || header.messageType == "c_script_end") {
_simulationQueue.Enqueue(header);
}
break;
}
}
} catch(Exception ex) {
try { PrintAsync("Python engine crashed. Message: " + ex.Message + "\n"); } catch { }
}
State = ConsoleState.Dead;
try { _client.CloseSocket(); } catch { }
}
private void PrintAsync(string message)
{
ThreadHelper.dispatcher.Dispatch(() => {
UnityPythonObject.Instance.Print(message);
});
}
private void PrintErrorAsync(string message)
{
ThreadHelper.dispatcher.Dispatch(() => {
UnityPythonObject.Instance.PrintError(message);
});
}
public void ScheduleExecution(string script)
{
try {
if (State == ConsoleState.Ready) {
RunScriptMessage msg = new RunScriptMessage() {
script = script,
clipboard = GetClipboardObjects(),
searchPaths = GetSearchPaths()
};
_stopWatch = new Stopwatch();
_stopWatch.Start();
_client.SendMsg(msg, "s_script_run");
State = ConsoleState.ScriptRunning;
}
}
catch(Exception e) {
State = ConsoleState.Dead;
UnityPythonObject.Instance.PrintError(e.ToString());
}
}
public void AbortScript()
{
State = ConsoleState.ScriptAborting;
_client.SendMsg(null, "s_script_abort");
}
private object[] GetClipboardObjects()
{
return SelectionTool.Instance.Clipboard.Where((obj) => obj.Exists).Select((obj) => obj.ToMessage()).ToArray();
}
private string[] GetSearchPaths()
{
return new string[]{
UnityPythonObject.Instance.scriptEditor.projectWorkspacePath,
Path.Combine(UnityPythonObject.Instance.scriptEditor.projectWorkspacePath, "imports"),
Path.Combine(UnityPythonObject.Instance.scriptEditor.projectWorkspacePath, "examples"),
Path.Combine(ModInfo.RemotePythonFolder, "imports"),
Path.Combine(ModInfo.RemotePythonFolder, "pypy")
};
}
public void SimulationStep()
{
do {
if (State == ConsoleState.ScriptRunning) {
while (_simulationQueue.Count > 0) {
MessageHeader header = (MessageHeader)_simulationQueue.Dequeue();
switch(header.messageType) {
case "c_script_end":
_stopWatch.Stop();
State = ConsoleState.Ready;
PrintAsync("Execution took " + _stopWatch.ElapsedMilliseconds + " ms\n");
break;
default:
_remoteFuncManager.HandleAPICall(header.payload, header.messageType, header.requestId);
break;
}
}
if(ExecuteSynchronously && State == ConsoleState.ScriptRunning) {
Thread.Sleep(1);
}
MoveItTool.instance.SimulationStep();
}
} while (State == ConsoleState.ScriptRunning && ExecuteSynchronously);
}
public static void KillInstance()
{
if (_instance != null) {
_instance.State = ConsoleState.Dead;
try {
TcpClient.process.Kill();
}
catch { }
}
}
public static void CreateInstance()
{
KillInstance();
_instance = new PythonConsole(ModInfo.SyncExecution.value);
}
}
public enum ConsoleState
{
Initializing,
Ready,
ScriptRunning,
ScriptAborting,
Dead
}
}