qtbridge_runtime/registry.rs
1// Copyright (C) 2026 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only
3
4//! The bridge's object index and deletion policy.
5//!
6//! Liveness is not held here: every attached object is kept alive by its
7//! proxy, so a Rust value lives exactly as long as its `QObject`, plus any
8//! user handles, which are plain `Rc<RefCell<T>>`s whose drops never
9//! tear anything down. The registry observes each object through a `Weak`
10//! reference and decides when the `QObject`s of Rust-created objects die.
11//!
12//! Entries are grouped by their registration [`Owner`]:
13//!
14//! * [`Owner::RustRegistry`]: Rust-created. Pinned to `CppOwnership` while
15//! Rust holds a handle, so the QML engine cannot delete it. The engine
16//! keeps the JS wrapper of a `CppOwnership` object alive for the whole
17//! object lifetime. [`collect_garbage`] therefore hands ownership to the
18//! engine by setting `JavaScriptOwnership` for objects without Rust
19//! interest (strong count is down to the proxy's own). The engine's
20//! garbage collector deletes them with exact reachability and takes
21//! down the value together with the proxy. An object that re-enters Rust
22//! is changed back to `CppOwnership`. Objects that were never wrapped
23//! with a JS wrapper are deleted directly when Rust interest vanishes.
24//! * [`Owner::Engine`]: QML-created. The engine (or a parent) deletes the
25//! `QObject`; the registry never does, and the entry only serves the
26//! proxy lookup.
27//!
28//! The `CppOwnership` flag guards only against the garbage collector:
29//! deletion paths that ignore the ownership flag (parents, components,
30//! engine death) can take a `QObject` of either kind. The registry entry
31//! is deleted together with the `QObject` but the Rust value then survives
32//! through user handles and gets a fresh `QObject` with `Owner::RustRegistry`
33//! attached on its next exposure.
34//!
35//! [`collect_garbage`] is triggered by the garbage collection of the
36//! QmlEngine and under allocation pressure (see `register`).
37//! A garbage collection cannot be observed with e.g. connecting to a
38//! signal, so we use a sentinel that is injected into the QML engine and
39//! that should be deleted on the next garbage collector cycle.
40
41use std::any::Any;
42use std::cell::{Cell, RefCell};
43use std::collections::HashMap;
44use std::rc::Weak;
45
46use qtbridge_type_lib::QObject;
47use qtbridge_type_lib::core::qobject;
48
49#[cxx::bridge]
50mod ffi {
51 unsafe extern "C++" {
52 include!("qtbridge-type-lib/src/core/qobject/cpp/qobject.h");
53 type QObject = qtbridge_type_lib::QObject;
54
55 include!("cpp/registry.h");
56 }
57
58 unsafe extern "C++" {
59 include!("qtbridge-type-lib/src/qml/qqmlapplicationengine/cpp/qqmlapplicationengine.h");
60 type QQmlApplicationEngine = qtbridge_type_lib::QQmlApplicationEngine;
61 }
62
63 #[namespace = "rust::bridge::registry"]
64 unsafe extern "C++" {
65 /// Whether any QML engine currently holds a JS wrapper for `obj`.
66 #[rust_name = has_live_js_wrapper]
67 unsafe fn hasLiveJsWrapper(obj: *const QObject) -> bool;
68
69 #[rust_name = set_cpp_ownership]
70 unsafe fn setCppOwnership(obj: *mut QObject);
71
72 #[rust_name = set_javascript_ownership]
73 unsafe fn setJavaScriptOwnership(obj: *mut QObject);
74
75 #[rust_name = is_javascript_ownership]
76 unsafe fn isJavaScriptOwnership(obj: *mut QObject) -> bool;
77
78 #[rust_name = install_gc_sentinel_impl]
79 fn installGcSentinel(engine: Pin<&mut QQmlApplicationEngine>);
80 }
81
82 #[namespace = "rust::bridge::registry"]
83 extern "Rust" {
84 fn collect_garbage();
85 }
86}
87
88/// Arms the automatic collection trigger on `engine` by creating a sentinel.
89///
90/// The sentinel is a dummy `QObject` with `JavaScriptOwnership` whose JS
91/// wrapper is referenced by nothing: the next garbage collection frees the
92/// wrapper and thereby deletes the sentinel, whose `destroyed()` signal runs
93/// [`collect_garbage`] and re-arms a new sentinel one event-loop turn later.
94/// [`crate::QApp`] arms this automatically; call it manually when driving a raw engine.
95pub fn install_gc_sentinel(engine: core::pin::Pin<&mut qtbridge_type_lib::QQmlApplicationEngine>) {
96 ffi::install_gc_sentinel_impl(engine);
97}
98
99/// ownership indicator:
100 #[derive(Clone, PartialEq)]
101 pub enum Owner {
102 /// The registry: pinned to `CppOwnership` while Rust holds a handle,
103 /// changed to `JavaScriptOwnership` by [`collect_garbage`] and then
104 /// finally deleted by the QML engine.
105 RustRegistry,
106 /// The QML engine which deletes its own objects.
107 Engine,
108}
109/// Address of the user Rust value, used as its registry key.
110pub(crate) type RustObjectAddress = *const u8;
111
112/// Address of the Rust proxy that connects the user value to its C++ QObject.
113pub(crate) type RustProxyAddress = *const u8;
114
115struct Entry {
116 /// Type-erased pointer to the object's `RustProxy`.
117 proxy: RustProxyAddress,
118 /// The attached [`QObject`]. Valid for as long as the entry exists: its
119 /// deletion tears down the proxy, whose `on_drop` unregisters the entry.
120 qobject: *mut QObject,
121 /// Observe Rust usage. RustProxy holds the strong reference and
122 /// guarantees liveness.
123 value: Weak<dyn Any>
124}
125
126/// Entries keyed by the address of the user value, grouped by owenerships.
127/// The sets retain their registration Owner druing Qt handovers.
128struct Entries {
129 registry_owned: HashMap<RustObjectAddress, Entry>,
130 engine_owned: HashMap<RustObjectAddress, Entry>
131}
132
133impl Entries {
134 fn get(&self, key: RustObjectAddress)-> Option<&Entry> {
135 self.registry_owned.get(&key).or_else(||self.engine_owned.get(&key))
136 }
137}
138
139impl Drop for Entries {
140 fn drop(&mut self) {
141 for (_, entry) in self.registry_owned.drain() {
142 unsafe { qobject::delete(entry.qobject) }; // Deletes both proxies
143 }
144 }
145}
146
147thread_local! {
148 static REGISTRY: RefCell<Entries> = RefCell::new(Entries {
149 registry_owned: HashMap::new(),
150 engine_owned: HashMap::new()
151 });
152}
153
154thread_local! {
155 static COLLECT_THRESHOLD: Cell<usize> = const { Cell::new(64) };
156}
157
158/// Registers an attached object
159pub(crate) fn register(
160 key: RustObjectAddress, proxy: RustProxyAddress, qobject: *mut QObject,
161 value: Weak<dyn Any>, owner: Owner
162) {
163 let registry_owned = owner == Owner::RustRegistry;
164 if registry_owned {
165 unsafe { ffi::set_cpp_ownership(qobject) };
166 }
167 REGISTRY.with_borrow_mut(|entries| {
168 debug_assert!(entries.get(key).is_none(), "Object is already registered");
169 let map = match owner {
170 Owner::RustRegistry => &mut entries.registry_owned,
171 Owner::Engine => &mut entries.engine_owned,
172 };
173 map.insert(key, Entry { proxy, qobject, value });
174 });
175 // If we reach a certain amount of QObjects, we will trigger a collect to
176 // clean up stale objects.
177 if registry_owned && registry_owned_count() >= COLLECT_THRESHOLD.get() {
178 collect_garbage();
179 }
180}
181
182/// Takes ownership back when a handed-over object re-enters Rust.
183pub(crate) fn repin(key: RustObjectAddress) {
184 REGISTRY.with_borrow(|entries| {
185 if let Some(entry) = entries.registry_owned.get(&key) {
186 unsafe { ffi::set_cpp_ownership(entry.qobject) };
187 }
188 });
189}
190
191/// Drops the entry for `key`; called from the proxy teardown when the
192/// `QObject` is deleted (by [`collect_garbage`] or by the engine). Entries
193/// of objects freed by [`collect_garbage`] are already extracted by then,
194/// and during registry teardown the map is being drained.
195pub(crate) fn unregister(key: RustObjectAddress) {
196 let _ = REGISTRY.try_with(|entries: &RefCell<Entries>| {
197 let mut entries = entries.borrow_mut();
198 entries.registry_owned.remove(&key)
199 .or_else(|| entries.engine_owned.remove(&key));
200 });
201}
202
203/// Returns the type-erased `RustProxy` pointer for `key`, or null when the
204/// object has no attached `QObject`.
205pub(crate) fn proxy_ptr(key: RustObjectAddress) -> RustProxyAddress {
206 REGISTRY.with_borrow(|entries| {
207 entries.get(key).map_or(std::ptr::null(), |entry| entry.proxy)
208 })
209}
210
211/// The number of objects the registry currently owns. Engine-owned objects are not included.
212/// Useful for leak checks.
213pub fn registry_owned_count() -> usize {
214 REGISTRY.with_borrow(|entries| entries.registry_owned.len())
215}
216
217/// The number of objects with an attached `QObject`, including both registry-owned and engine-owned
218/// entries. Useful for leak checks.
219pub fn attached_object_count() -> usize {
220 REGISTRY.with_borrow(|entries| entries.registry_owned.len() + entries.engine_owned.len())
221}
222
223
224/// Frees every object that is neither referenced from Rust nor reachable from
225/// QML.
226/// Runs automatically after every garbage collection if using [crate::QApp]
227/// and under allocation pressure; call it explicitly for deterministic
228/// reclamation points.
229pub fn collect_garbage() {
230 // Rust interest is the strong count above the registry's own reference.
231 // Objects the engine never wrapped are freed directly; wrapped ones are
232 // handed over to the engine, whose next garbage collection deletes them
233 // unless QML still reaches them.
234
235 // Freeing an object can release its references to other registered
236 // objects (e.g. children stored in fields), so iterate to a fixpoint.
237 loop {
238 // Extract first, act outside the borrow: deleting a QObject
239 // re-enters the registry through the proxy teardown's unregister.
240 let doomed: Vec<(Weak<dyn Any>, *mut QObject)> = REGISTRY.with_borrow_mut(|entries| {
241 entries.registry_owned.extract_if(|_key, entry| {
242 debug_assert!(entry.value.strong_count() >= 1);
243 if entry.value.strong_count() > 1 {
244 return false;
245 }
246 if unsafe { ffi::is_javascript_ownership(entry.qobject) } {
247 return false;
248 }
249 if unsafe { ffi::has_live_js_wrapper(entry.qobject) } {
250 // The wrapper of a CppOwned object never dies and we can
251 // therefore not track QML interest into the object. Hand
252 // the object to the engine in order to check QML interest.
253 // The engine will initiate the teardown.
254 unsafe { ffi::set_javascript_ownership(entry.qobject) };
255 return false;
256 }
257 // No Rust interest (Only strong reference is in the proxy)
258 // No QML interest (No JS Wrapper)
259 true
260 })
261 .map(|(_key, entry)| {
262 (entry.value, entry.qobject)
263 })
264 .collect()
265 });
266 if doomed.is_empty() {
267 break;
268 }
269 for (value, qobject) in doomed {
270 // Ensure that the Rust object is alive for the whole destructor
271 let keep_alive = value.upgrade();
272 assert!(keep_alive.is_some());
273 // Tears down the proxy pair; its on_drop removes the registry
274 // entry.
275 unsafe { qobject::delete(qobject) };
276 // Ours is the last reference: this frees the Rust object,
277 // running a user-provided Drop if there is one.
278 drop(keep_alive);
279 }
280 }
281 // Update the threshold on when we automatically collect QObjects.
282 // Twice the amount after a fresh sweep seems to be a good spot.
283 // The minimum value of 64 avoids collection on every few allocations.
284 // TODO: We might have to re-evaluate the values or this simplistic
285 // algorithm.
286 COLLECT_THRESHOLD.set((registry_owned_count() * 2).max(64));
287}