Repository navigation
Expand file tree
/
Copy pathPythonPlugin.cpp
More file actions
755 lines (641 loc) · 22.6 KB
/
Copy pathPythonPlugin.cpp
File metadata and controls
755 lines (641 loc) · 22.6 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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
#include "PythonBindings.h"
// DO NOT CHANGE THIS LINE.
// The plugin manager uses it to create and destroy the plugin instance.
REGISTER_PLUGIN(PythonPlugin)
PythonPlugin* PythonPlugin::Instance = nullptr;
namespace
{
const char* RunnerFileName = "<python plugin runner>";
// Executes code like interactive Python: value of the last expression is returned as repr().
// Exceptions are returned as text, SystemExit is caught too, so exit() in a script does not close application.
const char* RunnerCode = R"(
import ast, importlib.util, textwrap, tokenize, traceback
def _format_error(error):
if isinstance(error, SyntaxError):
return "".join(traceback.format_exception_only(type(error), error))
trace = error.__traceback__
while trace is not None and trace.tb_frame.f_code.co_filename == RUNNER_FILE_NAME:
trace = trace.tb_next
return "".join(traceback.format_exception(type(error), error, trace))
def _execute(code, file_name, namespace):
tree = ast.parse(textwrap.dedent(code), file_name, "exec")
last_expression = None
if tree.body and isinstance(tree.body[-1], ast.Expr):
last_expression = ast.Expression(tree.body.pop().value)
exec(compile(tree, file_name, "exec"), namespace)
if last_expression is None:
return ""
value = eval(compile(last_expression, file_name, "eval"), namespace)
return "" if value is None else repr(value)
def run(code, file_name, namespace):
try:
return True, _execute(code, file_name, namespace)
except BaseException as error:
return False, _format_error(error)
def run_file(file_path, namespace):
try:
with tokenize.open(file_path) as file:
code = file.read()
namespace["__file__"] = file_path
return True, _execute(code, file_path, namespace)
except BaseException as error:
return False, _format_error(error)
def evaluate(expression, namespace):
try:
return True, repr(eval(compile(textwrap.dedent(expression).strip(), "<expression>", "eval"), namespace))
except BaseException as error:
return False, _format_error(error)
def is_module_available(name):
try:
return importlib.util.find_spec(name) is not None
except (ImportError, ValueError):
return False
)";
const std::wstring PythonVersionPostfix = std::to_wstring(PY_MAJOR_VERSION) + std::to_wstring(PY_MINOR_VERSION);
const double ScriptThreadsJoinTimeoutInSeconds = 5.0;
// Runtime is next to Python DLL: in Debug or Release folder of plugin, or next to executable in games.
std::wstring GetPythonRuntimeDirectory()
{
HMODULE PythonModule = GetModuleHandleW((L"python" + PythonVersionPostfix + L".dll").c_str());
if (PythonModule == nullptr)
return L"";
std::wstring Path(32768, L'\0');
const DWORD Length = GetModuleFileNameW(PythonModule, Path.data(), static_cast<DWORD>(Path.size()));
Path.resize(Length);
const size_t LastSeparator = Path.find_last_of(L"\\/");
return LastSeparator == std::wstring::npos ? L"" : Path.substr(0, LastSeparator + 1);
}
std::string ToUTF8(const std::wstring& Text)
{
const int Length = WideCharToMultiByte(CP_UTF8, 0, Text.c_str(), -1, nullptr, 0, nullptr, nullptr);
std::string Result(Length > 0 ? Length - 1 : 0, '\0');
WideCharToMultiByte(CP_UTF8, 0, Text.c_str(), -1, Result.data(), Length, nullptr, nullptr);
return Result;
}
const char* GetCallbackTypeName(PythonPlugin::CallbackType Type)
{
switch (Type)
{
case PythonPlugin::CallbackType::Update: return "update";
case PythonPlugin::CallbackType::SceneAdded: return "scene added";
case PythonPlugin::CallbackType::SceneDeleting: return "scene deleting";
case PythonPlugin::CallbackType::Shutdown: return "shutdown";
default: return "unknown";
}
}
}
bool PythonPlugin::OnLoad()
{
MainThreadID = std::this_thread::get_id();
if (Py_IsInitialized())
{
// Plugin stays loaded, its functions fail while Python is not initialized by plugin.
LOG.Add("PythonPlugin::OnLoad: Python is already initialized by application, plugin could not use its own runtime", "PYTHON_PLUGIN", FE_LOG_ERROR);
return true;
}
// Inittab stays after Python is finalized, so after plugin is reloaded existing entry gets function from new DLL.
bool bModuleRegistered = false;
for (_inittab* Entry = PyImport_Inittab; Entry->name != nullptr; Entry++)
{
if (strcmp(Entry->name, "focalengine") == 0)
{
Entry->initfunc = PyInit_focalengine;
bModuleRegistered = true;
}
}
if (!bModuleRegistered && PyImport_AppendInittab("focalengine", PyInit_focalengine) == -1)
{
LOG.Add("PythonPlugin::OnLoad: Failed to register focalengine module", "PYTHON_PLUGIN", FE_LOG_ERROR);
return true;
}
const std::wstring RuntimeDirectory = GetPythonRuntimeDirectory();
if (RuntimeDirectory.empty())
{
LOG.Add("PythonPlugin::OnLoad: Folder of Python runtime is not found", "PYTHON_PLUGIN", FE_LOG_ERROR);
return true;
}
// Isolated config ignores Python that is installed on computer and its environment variables.
PyConfig Config;
PyConfig_InitIsolatedConfig(&Config);
Config.install_signal_handlers = 0;
PyStatus Status = PyConfig_SetString(&Config, &Config.home, RuntimeDirectory.c_str());
if (!PyStatus_Exception(Status))
{
Config.module_search_paths_set = 1;
Status = PyWideStringList_Append(&Config.module_search_paths, (RuntimeDirectory + L"python" + PythonVersionPostfix + L".zip").c_str());
}
if (!PyStatus_Exception(Status))
Status = PyWideStringList_Append(&Config.module_search_paths, RuntimeDirectory.c_str());
if (!PyStatus_Exception(Status))
Status = Py_InitializeFromConfig(&Config);
PyConfig_Clear(&Config);
if (PyStatus_Exception(Status))
{
LOG.Add("PythonPlugin::OnLoad: Python failed to start from \"" + ToUTF8(RuntimeDirectory) + "\": " + std::string(Status.err_msg != nullptr ? Status.err_msg : "unknown error"), "PYTHON_PLUGIN", FE_LOG_ERROR);
return true;
}
try
{
py::module_ Sys = py::module_::import("sys");
py::module_ Engine = py::module_::import("focalengine");
Sys.attr("stdout") = Engine.attr("_OutputStream")(false);
Sys.attr("stderr") = Engine.attr("_OutputStream")(true);
py::module_ Builtins = py::module_::import("builtins");
Runner = py::dict();
Runner["__builtins__"] = Builtins;
Runner["RUNNER_FILE_NAME"] = RunnerFileName;
Builtins.attr("exec")(Builtins.attr("compile")(RunnerCode, RunnerFileName, "exec"), Runner);
}
catch (py::error_already_set& Error)
{
LOG.Add("PythonPlugin::OnLoad: Python started, but plugin setup failed: " + FormatException(Error), "PYTHON_PLUGIN", FE_LOG_ERROR);
Runner = py::object();
Py_FinalizeEx();
return true;
}
PythonVersion = Py_GetVersion();
PythonVersion = PythonVersion.substr(0, PythonVersion.find(' '));
// GIL is released, so threads started by scripts could run between frames.
MainThreadState = PyEval_SaveThread();
bInitialized = true;
Instance = this;
LOG.Add("PythonPlugin::OnLoad: Python " + PythonVersion + " started from \"" + ToUTF8(RuntimeDirectory) + "\"", "PYTHON_PLUGIN");
return true;
}
void PythonPlugin::OnUnload()
{
if (bInitialized)
{
PyEval_RestoreThread(MainThreadState);
MainThreadState = nullptr;
// Main thread will not run queued calls anymore, so threads that wait for them get CancelledError instead of waiting forever,
// that includes threads that shutdown callbacks wait for. Calls made after this are cancelled right away.
{
std::lock_guard<std::mutex> Lock(QueueMutex);
bShuttingDown = true;
}
CancelQueuedCalls();
CallCallbacks(CallbackType::Shutdown, py::object());
Callbacks.clear();
for (size_t i = 0; i < static_cast<size_t>(CallbackType::Count); i++)
CallbackCount[i] = 0;
Runner = py::object();
FlushPendingLogLines();
// Py_FinalizeEx waits for threads that are not daemon threads without time limit, so one stuck thread would hang application on exit.
const std::vector<std::string> RunningThreadNames = JoinScriptThreads(ScriptThreadsJoinTimeoutInSeconds);
if (RunningThreadNames.empty())
{
if (Py_FinalizeEx() < 0)
LOG.Add("PythonPlugin::OnUnload: Python reported an error while finalizing", "PYTHON_PLUGIN", FE_LOG_WARNING);
}
else
{
std::string ThreadNames;
for (size_t i = 0; i < RunningThreadNames.size(); i++)
ThreadNames += (i == 0 ? "\"" : ", \"") + RunningThreadNames[i] + "\"";
LOG.Add("PythonPlugin::OnUnload: Python is not finalized, because threads " + ThreadNames + " are still running", "PYTHON_PLUGIN", FE_LOG_WARNING);
// These threads still run code of Python and of bindings, so plugin module and Python should stay loaded.
HMODULE PluginModule = nullptr;
GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, reinterpret_cast<LPCWSTR>(&PythonPlugin::Instance), &PluginModule);
}
FlushPendingLogLines();
bInitialized = false;
Instance = nullptr;
// Bindings now report that plugin is not loaded, threads that are still running could finish with that.
if (!RunningThreadNames.empty())
PyEval_SaveThread();
}
// Owners unregister their functions before they are unloaded, functions that are left could belong to modules that are already unloaded.
if (!NativeFunctions->empty())
{
std::string FunctionNames;
for (const auto& Entry : *NativeFunctions)
FunctionNames += (FunctionNames.empty() ? "\"" : ", \"") + Entry.first + "\" of \"" + Entry.second.OwnerName + "\"";
LOG.Add("PythonPlugin::OnUnload: Native functions " + FunctionNames + " were not unregistered, they are leaked, because destroying them could run code of unloaded modules", "PYTHON_PLUGIN", FE_LOG_WARNING);
static_cast<void>(NativeFunctions.release());
NativeFunctions = std::make_unique<std::unordered_map<std::string, NativeFunctionEntry>>();
}
EditorAPI = nullptr;
}
void PythonPlugin::OnUpdate(double DeltaTime)
{
if (!bInitialized)
return;
if (!bQueueHasCalls && CallbackCount[static_cast<size_t>(CallbackType::Update)] == 0)
return;
py::gil_scoped_acquire Acquire;
RunQueuedCalls();
CallCallbacks(CallbackType::Update, py::float_(DeltaTime));
}
void PythonPlugin::OnSceneAdded(FEScene* Scene)
{
if (!bInitialized || CallbackCount[static_cast<size_t>(CallbackType::SceneAdded)] == 0)
return;
py::gil_scoped_acquire Acquire;
CallCallbacks(CallbackType::SceneAdded, py::cast(PythonScene{ Scene->GetID() }));
}
void PythonPlugin::OnSceneDeleting(FEScene* Scene)
{
if (!bInitialized || CallbackCount[static_cast<size_t>(CallbackType::SceneDeleting)] == 0)
return;
py::gil_scoped_acquire Acquire;
CallCallbacks(CallbackType::SceneDeleting, py::cast(PythonScene{ Scene->GetID() }));
}
bool PythonPlugin::IsInitialized() const
{
return bInitialized;
}
std::string PythonPlugin::GetPythonVersion() const
{
return PythonVersion;
}
PythonPluginInterface::ExecutionResult PythonPlugin::RunString(const std::string& Code, bool bIsolatedNamespace)
{
return Execute([&](py::dict Namespace) { return Runner["run"](Code, "<string>", Namespace); }, bIsolatedNamespace);
}
PythonPluginInterface::ExecutionResult PythonPlugin::RunFile(const std::string& FilePath, bool bIsolatedNamespace)
{
return Execute([&](py::dict Namespace) { return Runner["run_file"](FilePath, Namespace); }, bIsolatedNamespace);
}
PythonPluginInterface::ExecutionResult PythonPlugin::Evaluate(const std::string& Expression)
{
return Execute([&](py::dict Namespace) { return Runner["evaluate"](Expression, Namespace); }, false);
}
PythonPluginInterface::ExecutionResult PythonPlugin::Execute(const std::function<py::object(py::dict)>& Run, bool bIsolatedNamespace)
{
ExecutionResult Result;
if (!bInitialized)
{
Result.Error = "Python is not initialized";
return Result;
}
py::gil_scoped_acquire Acquire;
std::string* PreviousCapturedOutput = CapturedOutput;
const std::thread::id PreviousCaptureThreadID = CaptureThreadID;
CapturedOutput = &Result.Output;
CaptureThreadID = std::this_thread::get_id();
try
{
py::tuple RunResult = Run(GetNamespace(bIsolatedNamespace));
Result.bSuccess = RunResult[0].cast<bool>();
(Result.bSuccess ? Result.Value : Result.Error) = RunResult[1].cast<std::string>();
}
catch (py::error_already_set& Error)
{
Result.bSuccess = false;
Result.Error = FormatException(Error);
}
catch (const std::exception& Exception)
{
Result.bSuccess = false;
Result.Error = Exception.what();
}
CapturedOutput = PreviousCapturedOutput;
CaptureThreadID = PreviousCaptureThreadID;
return Result;
}
py::dict PythonPlugin::GetNamespace(bool bIsolated)
{
if (!bIsolated)
return py::module_::import("__main__").attr("__dict__");
py::dict Namespace;
Namespace["__name__"] = "__main__";
Namespace["__builtins__"] = py::module_::import("builtins");
return Namespace;
}
void PythonPlugin::ResetNamespace()
{
if (!bInitialized)
return;
py::gil_scoped_acquire Acquire;
try
{
py::dict Namespace = GetNamespace(false);
Namespace.clear();
Namespace["__name__"] = "__main__";
Namespace["__builtins__"] = py::module_::import("builtins");
}
catch (py::error_already_set& Error)
{
LOG.Add("PythonPlugin::ResetNamespace: " + FormatException(Error), "PYTHON_PLUGIN", FE_LOG_ERROR);
}
}
bool PythonPlugin::AddModuleSearchPath(const std::string& DirectoryPath)
{
if (!bInitialized || !FILE_SYSTEM.DoesDirectoryExist(DirectoryPath))
return false;
py::gil_scoped_acquire Acquire;
try
{
const std::string AbsolutePath = FILE_SYSTEM.GetAbsolutePath(DirectoryPath);
py::list Path = py::module_::import("sys").attr("path");
if (!Path.contains(AbsolutePath))
Path.append(AbsolutePath);
return true;
}
catch (py::error_already_set& Error)
{
LOG.Add("PythonPlugin::AddModuleSearchPath: " + FormatException(Error), "PYTHON_PLUGIN", FE_LOG_ERROR);
return false;
}
}
bool PythonPlugin::IsModuleAvailable(const std::string& ModuleName)
{
if (!bInitialized)
return false;
py::gil_scoped_acquire Acquire;
try
{
return Runner["is_module_available"](ModuleName).cast<bool>();
}
catch (py::error_already_set&)
{
return false;
}
}
bool PythonPlugin::RegisterNativeFunction(const std::string& OwnerName, const std::string& FunctionName, NativeFunction Function)
{
if (!IsMainThread())
{
LOG.Add("PythonPlugin::RegisterNativeFunction: \"" + FunctionName + "\" of \"" + OwnerName + "\" is not registered, because it should be registered on main thread", "PYTHON_PLUGIN", FE_LOG_ERROR);
return false;
}
if (FunctionName.empty() || !Function)
{
LOG.Add("PythonPlugin::RegisterNativeFunction: Function of \"" + OwnerName + "\" is not registered, because its name or function is empty", "PYTHON_PLUGIN", FE_LOG_ERROR);
return false;
}
const auto ExistingEntry = NativeFunctions->find(FunctionName);
if (ExistingEntry != NativeFunctions->end())
{
LOG.Add("PythonPlugin::RegisterNativeFunction: \"" + FunctionName + "\" of \"" + OwnerName + "\" is not registered, because \"" + ExistingEntry->second.OwnerName + "\" already registered function with that name", "PYTHON_PLUGIN", FE_LOG_WARNING);
return false;
}
(*NativeFunctions)[FunctionName] = NativeFunctionEntry{ OwnerName, std::move(Function) };
return true;
}
void PythonPlugin::UnregisterNativeFunctions(const std::string& OwnerName)
{
if (!IsMainThread())
{
LOG.Add("PythonPlugin::UnregisterNativeFunctions: Functions of \"" + OwnerName + "\" are not unregistered, because they should be unregistered on main thread", "PYTHON_PLUGIN", FE_LOG_ERROR);
return;
}
auto Iterator = NativeFunctions->begin();
while (Iterator != NativeFunctions->end())
{
if (Iterator->second.OwnerName == OwnerName)
{
Iterator = NativeFunctions->erase(Iterator);
}
else
{
Iterator++;
}
}
}
std::string PythonPlugin::CallNativeFunction(const std::string& FunctionName, const std::string& ArgumentsJSON)
{
const auto Entry = NativeFunctions->find(FunctionName);
if (Entry == NativeFunctions->end())
throw py::key_error("Native function \"" + FunctionName + "\" is not registered, focalengine.get_native_function_names() lists registered functions");
// Copy keeps function alive even if it unregisters itself while it runs.
const NativeFunction Function = Entry->second.Function;
try
{
// Other Python threads could run while C++ function works.
py::gil_scoped_release Release;
return Function(ArgumentsJSON);
}
catch (const std::exception& Exception)
{
throw std::runtime_error("Native function \"" + FunctionName + "\" failed: " + Exception.what());
}
catch (...)
{
throw std::runtime_error("Native function \"" + FunctionName + "\" failed with unknown exception");
}
}
std::vector<std::string> PythonPlugin::GetNativeFunctionNames() const
{
std::vector<std::string> Result;
for (const auto& Entry : *NativeFunctions)
Result.push_back(Entry.first);
std::sort(Result.begin(), Result.end());
return Result;
}
void PythonPlugin::SetEditorAPI(FEEditorAPI* Editor)
{
EditorAPI = Editor;
}
FEEditorAPI* PythonPlugin::GetEditorAPI() const
{
return EditorAPI;
}
int PythonPlugin::AddCallback(CallbackType Type, py::object Function)
{
// Callback added while plugin is unloading would never be called and would outlive Python.
if (bShuttingDown)
throw std::runtime_error("Python is shutting down, callbacks could not be added");
Callback NewCallback;
NewCallback.ID = NextCallbackID++;
NewCallback.Type = Type;
NewCallback.Function = Function;
Callbacks.push_back(NewCallback);
CallbackCount[static_cast<size_t>(Type)]++;
return NewCallback.ID;
}
bool PythonPlugin::RemoveCallback(int CallbackID)
{
for (size_t i = 0; i < Callbacks.size(); i++)
{
if (Callbacks[i].ID != CallbackID)
continue;
CallbackCount[static_cast<size_t>(Callbacks[i].Type)]--;
Callbacks.erase(Callbacks.begin() + i);
return true;
}
return false;
}
void PythonPlugin::CallCallbacks(CallbackType Type, const py::object& Argument)
{
// Callbacks could add or remove callbacks, so list is copied.
std::vector<Callback> CallbacksToCall;
for (size_t i = 0; i < Callbacks.size(); i++)
{
if (Callbacks[i].Type == Type)
CallbacksToCall.push_back(Callbacks[i]);
}
for (size_t i = 0; i < CallbacksToCall.size(); i++)
{
std::string Error;
try
{
if (Argument)
CallbacksToCall[i].Function(Argument);
else
CallbacksToCall[i].Function();
}
catch (py::error_already_set& Exception)
{
Error = FormatException(Exception);
}
catch (const std::exception& Exception)
{
Error = Exception.what();
}
if (Error.empty())
continue;
// Otherwise update callback with error would fill log every frame.
RemoveCallback(CallbacksToCall[i].ID);
LOG.Add("Python " + std::string(GetCallbackTypeName(Type)) + " callback raised an exception and was removed:\n" + Error, "PYTHON", FE_LOG_ERROR);
}
}
py::object PythonPlugin::CallOnMainThread(py::object Function)
{
QueuedCall Call;
Call.Function = Function;
Call.Future = py::module_::import("concurrent.futures").attr("Future")();
if (IsMainThread())
{
RunQueuedCall(Call);
return Call.Future;
}
{
std::lock_guard<std::mutex> Lock(QueueMutex);
if (!bShuttingDown)
{
Queue.push_back(Call);
bQueueHasCalls = true;
return Call.Future;
}
}
// Main thread does not run queued calls while plugin is unloading, so waiting thread gets CancelledError right away.
Call.Future.attr("cancel")();
return Call.Future;
}
void PythonPlugin::RunQueuedCall(QueuedCall& Call)
{
try
{
if (!Call.Future.attr("set_running_or_notify_cancel")().cast<bool>())
return;
try
{
Call.Future.attr("set_result")(Call.Function());
}
catch (py::error_already_set& Error)
{
Call.Future.attr("set_exception")(Error.value());
}
}
catch (py::error_already_set& Error)
{
LOG.Add("PythonPlugin::RunQueuedCall: " + FormatException(Error), "PYTHON_PLUGIN", FE_LOG_ERROR);
}
}
void PythonPlugin::RunQueuedCalls()
{
std::vector<QueuedCall> CallsToRun;
{
std::lock_guard<std::mutex> Lock(QueueMutex);
CallsToRun.swap(Queue);
bQueueHasCalls = false;
}
for (size_t i = 0; i < CallsToRun.size(); i++)
RunQueuedCall(CallsToRun[i]);
}
void PythonPlugin::CancelQueuedCalls()
{
std::vector<QueuedCall> CallsToCancel;
{
std::lock_guard<std::mutex> Lock(QueueMutex);
CallsToCancel.swap(Queue);
bQueueHasCalls = false;
}
for (size_t i = 0; i < CallsToCancel.size(); i++)
{
try
{
CallsToCancel[i].Future.attr("cancel")();
}
catch (py::error_already_set&) {}
}
}
std::vector<std::string> PythonPlugin::JoinScriptThreads(double TimeoutInSeconds)
{
std::vector<std::string> RunningThreadNames;
try
{
py::module_ Threading = py::module_::import("threading");
py::module_ Time = py::module_::import("time");
py::object CurrentThread = Threading.attr("current_thread")();
const double Deadline = Time.attr("monotonic")().cast<double>() + TimeoutInSeconds;
// Threads could start other threads while they are joined, so list is taken again after each join.
while (true)
{
std::vector<py::object> RunningThreads;
py::list Threads = Threading.attr("enumerate")();
for (py::handle Thread : Threads)
{
if (!Thread.is(CurrentThread) && !Thread.attr("daemon").cast<bool>() && Thread.attr("is_alive")().cast<bool>())
RunningThreads.push_back(py::reinterpret_borrow<py::object>(Thread));
}
const double RemainingTime = Deadline - Time.attr("monotonic")().cast<double>();
if (RunningThreads.empty() || RemainingTime <= 0.0)
{
for (size_t i = 0; i < RunningThreads.size(); i++)
RunningThreadNames.push_back(RunningThreads[i].attr("name").cast<std::string>());
break;
}
RunningThreads[0].attr("join")(RemainingTime);
}
}
catch (py::error_already_set& Error)
{
LOG.Add("PythonPlugin::JoinScriptThreads: " + FormatException(Error), "PYTHON_PLUGIN", FE_LOG_ERROR);
}
return RunningThreadNames;
}
void PythonPlugin::WriteOutput(const std::string& Text, bool bErrorStream)
{
if (CapturedOutput != nullptr && std::this_thread::get_id() == CaptureThreadID)
{
*CapturedOutput += Text;
return;
}
std::string& PendingLine = PendingLogLines[bErrorStream ? 1 : 0];
PendingLine += Text;
size_t LineEnd = PendingLine.find('\n');
while (LineEnd != std::string::npos)
{
LOG.Add(PendingLine.substr(0, LineEnd), "PYTHON", bErrorStream ? FE_LOG_WARNING : FE_LOG_INFO);
PendingLine.erase(0, LineEnd + 1);
LineEnd = PendingLine.find('\n');
}
}
void PythonPlugin::FlushPendingLogLines()
{
for (size_t i = 0; i < 2; i++)
{
if (!PendingLogLines[i].empty())
LOG.Add(PendingLogLines[i], "PYTHON", i == 1 ? FE_LOG_WARNING : FE_LOG_INFO);
PendingLogLines[i].clear();
}
}
bool PythonPlugin::IsMainThread() const
{
return std::this_thread::get_id() == MainThreadID;
}
std::string PythonPlugin::FormatException(py::error_already_set& Error)
{
try
{
py::object Lines = py::module_::import("traceback").attr("format_exception")(Error.type(), Error.value(), Error.trace());
return py::str("").attr("join")(Lines).cast<std::string>();
}
catch (py::error_already_set&)
{
return Error.what();
}
}