|
| 1 | +#include <QQuickWindow> |
| 2 | + |
1 | 3 | #include "jlcxx/jlcxx.hpp" |
2 | 4 |
|
3 | 5 | #include "foreign_thread_manager.hpp" |
@@ -34,6 +36,53 @@ void ForeignThreadManager::clear(QThread* main_thread) |
34 | 36 | m_mutex.unlock(); |
35 | 37 | } |
36 | 38 |
|
| 39 | +void ForeignThreadManager::add_window(QQuickItem* item) |
| 40 | +{ |
| 41 | + QObject::connect(item, &QQuickItem::windowChanged, [item, m_main_gc_state = JL_GC_STATE_UNSAFE, m_render_gc_state = JL_GC_STATE_UNSAFE] (QQuickWindow* w) mutable |
| 42 | + { |
| 43 | + if (w == nullptr) |
| 44 | + { |
| 45 | + return; |
| 46 | + } |
| 47 | + item->connect(w, &QQuickWindow::sceneGraphInitialized, [] () |
| 48 | + { |
| 49 | + // Adopt the render thread when it is first initialized |
| 50 | + ForeignThreadManager::instance().add_thread(QThread::currentThread()); |
| 51 | + }); |
| 52 | + item->connect(w, &QQuickWindow::afterAnimating, [&m_main_gc_state] () |
| 53 | + { |
| 54 | + // afterAnimating is the last signal sent before locking the main loop, so indicate |
| 55 | + // that the main loop is in a safe state for the Julia GC to run |
| 56 | + jl_ptls_t ptls = jl_current_task->ptls; |
| 57 | + m_main_gc_state = jl_gc_safe_enter(ptls); |
| 58 | + ptls->engine_nqueued++; |
| 59 | + }); |
| 60 | + item->connect(w, &QQuickWindow::beforeRendering, w, [&m_main_gc_state] () |
| 61 | + { |
| 62 | + // beforeRendering is the first signal sent after unlocking the main thread, so restore |
| 63 | + // the Julia GC state here. Queued connection so this is executed on the main thread |
| 64 | + jl_ptls_t ptls = jl_current_task->ptls; |
| 65 | + jl_gc_safe_leave(ptls, m_main_gc_state); |
| 66 | + ptls->engine_nqueued--; |
| 67 | + }, Qt::QueuedConnection); |
| 68 | + item->connect(w, &QQuickWindow::afterFrameEnd, w, [&m_render_gc_state] () |
| 69 | + { |
| 70 | + // After the rendering is done, the render thread may block for event handling, so we mark it as in a GC safe state |
| 71 | + // to prevent deadlock |
| 72 | + jl_ptls_t ptls = jl_current_task->ptls; |
| 73 | + m_render_gc_state = jl_gc_safe_enter(ptls); |
| 74 | + ptls->engine_nqueued++; |
| 75 | + }, Qt::DirectConnection); |
| 76 | + item->connect(w, &QQuickWindow::beforeFrameBegin, w, [&m_render_gc_state] () |
| 77 | + { |
| 78 | + // Reset GC state when the render thread might execute Julia code again |
| 79 | + jl_ptls_t ptls = jl_current_task->ptls; |
| 80 | + jl_gc_safe_leave(ptls, m_render_gc_state); |
| 81 | + ptls->engine_nqueued--; |
| 82 | + }, Qt::DirectConnection); |
| 83 | + }); |
| 84 | +} |
| 85 | + |
37 | 86 | ForeignThreadManager::ForeignThreadManager() |
38 | 87 | { |
39 | 88 | } |
0 commit comments